Thylacine 42 147
Quagga 34 18
Baiji 40 116
####
Name : Thylacine
Latitude : 42
Longitude : 147
Name : Quagga
Latitude : 34
Longitude : 18
Name : Baiji
Latitude : 40
Longitude : 116
####
# Always start your scripts with strict and warnings.
use strict;
use warnings;
# With "use strict" you must declare all variables before use
# (this catches errors when you misspell a variable name, for example).
# So we put a "my" in front of @speciesList and others below to declare
# them as lexical variables, which have a scope from the point of
# declaration to end of scope (i.e. end of block or end of file).
my @speciesList = qw(Name Latitude Longitude);
# Put "Mammal.txt" into a variable to avoid having to repeat it.
my $infile = "Mammal.txt";
# BTW, instead of hard-wiring $infile to "Mammal.txt" above
# you could now accept it as a command line argument like so:
# my $infile = shift or die "usage: $0 filename\n";
# Use three-argument open and a lexical file handle.
# Also check if the open fails and die with a useful message if so.
open my $MAMMALS, "<", $infile or die "error: open '$infile': $!";
# Use explicit lexical variables rather than $_
while (my $line = <$MAMMALS>) {
my %data;
@data{@speciesList} = split /\t/, $line, scalar @speciesList;
foreach my $species (@speciesList) {
printf "%-10.10s : %s\n", $species, $data{$species};
}
}
close $MAMMALS;
####
# This is a species file
Thylacine Lat=42 Long=147
Quagga Lat=34 Long=18
Baiji Lat=40 Long=116