#!/usr/bin/perl

# polygon_area( @xy )
#   Compute the area of a polygon using determinants.  The points
#   are supplied as ( $x0, $y0, $x1, $y1, $x2, $y2, ....)
#

sub polygon_area {
    my @xy = @_;

    my $A = 0;                          # The area.

    # Instead of wrapping the loop at its end
    # wrap it right from the beginning: the [-2, -1] below.
    for ( my ( $xa, $ya ) = @xy[ -2, -1 ];
          my ( $xb, $yb ) = splice @xy, 0, 2;
          ( $xa, $ya ) = ( $xb, $yb ) ) { # On to the next point.
        $A += determinant( $xa, $ya, $xb, $yb );
    }

    # If the points were listed in counterclockwise order, $A
    # will be negative here, so we take the absolute value.

    return abs $A / 2;
}

print polygon_area( 0, 1,  1, 0,  3, 2,  2, 3,  0, 2 ), "\n";

print polygon_area( 0, 1,  1, 0,  0, 2,  3, 2,  2, 3 ), "\n";

# determinant( $x0, $y0, $x1, $y1 )
#   Computes the determinant given the four elements of a matrix
#   as arguments.
#
sub determinant { $_[0] * $_[3] - $_[1] * $_[2]} 



