Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Greetings,

I would like to parse an input file of form:

USA:CA:Los Angeles
USA:CA:San Francisco
USA:NY:New York
CAN:Alb:Edmonton
CAN:Alb:Calgary

And output something like this:

The states in the USA are: NY, CA.
The cities in NY are: New York

Thanks!

Replies are listed 'Best First'.
Re: references // nested data structure
by gellyfish (Monsignor) on Feb 10, 2002 at 18:55 UTC

    OK, This is the code :

    #!/usr/bin/perl -w use strict; my %stuff; while(<DATA>) { chomp; my ( $country,$state,$city) = split /:/; push @{$stuff{$country}->{$state}},$city; } foreach my $country ( keys %stuff ) { print "The states in $country are ",join ",",keys %{$stuff{$country +}},"\n"; foreach my $state ( keys %{$stuff{$country}} ) { print "The cities in $state are ", join ",", @{$stuff{$country}->{$state}},"\n"; } } __DATA__ USA:CA:Los Angeles USA:CA:San Francisco USA:NY:New York CAN:Alb:Edmonton CAN:Alb:Calgary

    Now read perldsc and come back if you have any questions :)

    /J\

Re: references // nested data structure
by rdfield (Priest) on Feb 10, 2002 at 18:28 UTC
    Read perldsc, particularly hashes of hashes. Everything will become clear.

    rdfield