#!/usr/bin/perl

# polygon_perimeter( @xy )
#   Compute the perimeter length of a polygon.  The points
#   are supplied as ( $x0, $y0, $x1, $y1, $x2, $y2, ....)
#

sub polygon_perimeter {
    my @xy = @_;

    my $P = 0;                       # The perimeter length.

    # 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.
        $P += distance( $xa, $ya, $xb, $yb );
    }

    return $P;
}

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

# distance( @p ) computes the Euclidean distance between two
# d-dimensional points, given 2 * d coordinates.  For example, a pair of
# 3-D points should be provided as ( $x0, $y0, $z0, $x1, $y1, $z1 ).

sub distance {
    my @p = @_;                 # The coordinates of the points.
    my $d = @p / 2;             # The number of dimensions.

    # The case of two dimensions is optimized.
    return sqrt( ($_[0] - $_[2])**2 + ($_[1] - $_[3])**2 )
        if $d == 2;

    my $S = 0;                  # The sum of the squares.
    my @p0 = splice @p, 0, $d;  # The starting point.

    for ( my $i = 0; $i < $d; $i++ ) {
        my $di = $p0[ $i ] - $p[ $i ];  # Difference...
        $S += $di * $di;                # ...squared and summed.
    }

    return sqrt( $S );
}
