views:

217

answers:

3

Hi everyone,

I am new to Perl. I need to define a data structure in Perl that looks like this:

  city 1 -> street 1 - [ name , no of house , senior people ]
            street 2 - [ name , no of house , senior people ]


  city 2 -> street 1 - [ name , no of house , senior people ]
            street 2 - [ name , no of house , senior people ]

How can I acheive this?

+4  A: 

I found the answer like

my %city ;

 $city{$c_name}{$street} = [ $name , $no_house , $senior];

i can generate in this way

Sam
Do you have this information in a file or spreadsheet or database of some kind? I doubt that you want to use your program purely for data entry, so it would be easier to figure out the structure of the data and then read the records directly into the complex data structure. (Note that you already have one typo - $stret for $street. Hand entering a lot of data is very error prone.)
Telemachus
thank you very much sir
Sam
+2  A: 

Here is an another example using a hash reference:

my $data = {
    city1 => {
        street1 => ['name', 'house no', 'senior people'],
        street2 => ['name','house no','senior people'],
    },
    city2 => {
        street1 => etc...
        ...
    }
};

You then can access the data the following way:

$data->{'city1'}->{'street1'}->[0];

Or:

my @street_data = @{$data->{'city1'}->{'street1'}};
print @street_data;
Logan
You only need `->`, where it is obvious that you are working against a reference. So this `$data->{'city1'}{'street1'}[0];` would work just as well.
Brad Gilbert
+1  A: 

The Perl Data Structures Cookbook, perldsc, may be able to help. It has examples showing you how to create common data structures.

brian d foy