Wednesday, March 31, 2010

Perl Reference

Say you have a file like this.

Chicago, USA
Frankfurt, Germany
Berlin, Germany
Washington, USA
Helsinki, Finland
New York, USA

We need an output like below.

Finland: Helsinki.
Germany: Berlin, Frankfurt.
USA: Chicago, New York, Washington.

To do this it would be good to use perl references as below

my %table;
while (<>) {
my ($city, $country) = split /, /;
$table{$country} = [] unless exists $table{$country};
push @{$table{$country}}, $city;
foreach $country (sort keys %table) {
print "$country: ";
my @cities = @{$table{$country}};
print join ', ', sort @cities;
print ".\n";

More explanation on references is here

No comments: