Introducing UNIX and Linux |
PerlOverview |
Answer to chapter 12 question 3
# Process the first argument
open(DATA, $ARGV[0]) || die "Cannot open data file";
# Initialise running total
$length=0.0;
# Data file must have at least one line
# @oldcoordinate holds the previous line, and
# @coordinate the current line
if () {
# Extract the fields in the first line into
# the array @oldcoordinate
@oldcoordinate = split;
} else {
# Terminate if the data file is empty
die "No data";
}
# Loop through the lines of the file
while () {
# The current leg is calculated by
# subtracting the new coordinated from
# the old
@coordinate = split;
$x = $coordinate[0] - $oldcoordinate[0];
$y = $coordinate[1] - $oldcoordinate[1];
# Use Pythagoras' Theorem!
$d = sqrt ( $x*$x + $y*$y);
# Update the running total
$length += $d;
# The new line now becomes the previous
# coordinate
@oldcoordinate = @coordinate;
}
# Tidy up the open file handle
close (DATA);
# Finally, output the answer
printf "The journey length is %0.2f km.\n", $length;
|
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck