Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Please help, (perl hash)

by degit (Initiate)
on May 16, 2011 at 12:50 UTC ( [id://905064]=perlquestion: print w/replies, xml ) Need Help??

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

I have been working in a perl code and been having a problem, especially in using the "hash". I am a newbie in perl, i would appreciate some help.

This is a simple scenario...

We have Town A to Z and they have streets 1 to 9 and each street has different number of houses...

I would like to find out how to represent the data- eg. G6 = number of houses in town G street 6...

and such information sassociated with the keys? PLease help?

Update

Dear perlmonks,
Thanks for everyone who took time and effort to answer my question, as well as giving pointers to how it can be solved.

Just to correct thezip who says this is a homework, it actually isnt homework. I actually am not a student, and was programming before i got to the point i dint know how to express the "hash-a-hash" scenario where, some things change (eg towns and stret names) but some value associated with it doesnt change- (all streets in all towns have a house(s)) - probably the reason I re edited the question to something about mutants and all which was more complicated but i[ agree the house scenario was teh simplest and best way i could think of expressing the idea.
I wouldnt have had a problem pasted my code upto the point of hashes, but what i was coding was nothing related to houses, so i just simplified into the scenario, since i knew the exact problem i hit and what i wanted to solve.
I have managed to follow through and i appreciate the help, with the bits and pieces of code, and pointers of wisdom, and I pass my thanks to sundial for the really cool explanation, toolic, javafun, AnomalousMonk, anonymized user 468275 -- who by the way just showed a new approach in case any of use run into such a scenario :) And Of course, Thanks mariner :)

NB i am new, i dont know yet how to start a thread, so i end up overwriting the initial post (sorry Mariner!)

Replies are listed 'Best First'.
Re: Please help, (perl hash)
by toolic (Bishop) on May 16, 2011 at 12:56 UTC
    You could use HASHES OF HASHES
    my %town; $town{G}{6} = 7; # 7 houses on street 6 in town G

    Update: Here is degit's original question:

    I have been working in a perl code and been having a problem, especially in using the "hash". I am a newbie in perl, i would appreciate some help. This is a simple scenario... We have Town A to Z and they have streets 1 to 9 and each street has different number of houses... I would like to find out how to represent the data- eg. G6 = number of houses in town G street 6... and such information sassociated with the keys? PLease help?
Re: Please help, (perl hash)
by AnomalousMonk (Archbishop) on May 16, 2011 at 13:57 UTC

    What the other respondents have said, except that you...

    would like the street to be the key (so that it is easy to loop through, and from that point, i can get the town and the number of houses)...

    so I would organize the data a bit differently. There is an Oak street in Oakdale city, a Pine street in Pinehill city, and both cities have a Main street.

    >perl -wMstrict -le "my %streets = ( Oak => { Oakdale => 23 }, Pine => { Pinehill => 45 }, Main => { Oakdale => 67, Pinehill => 89, }, ); ;; for my $street (keys %streets) { for my $city (keys %{ $streets{$street} }) { printf qq{%s street in %s city has %d houses \n}, $street, $city, $streets{$street}{$city}; } } " Oak street in Oakdale city has 23 houses Pine street in Pinehill city has 45 houses Main street in Pinehill city has 89 houses Main street in Oakdale city has 67 houses
Re: Please help, (perl hash)
by marinersk (Priest) on May 16, 2011 at 15:22 UTC

    degit,

    Sorry to repeat but it seems pieces of your answers are scattered across several replies.

    Your Stated Requirements:

    1. Use a hash
    2. Track towns A-Z
    3. Track streets 1-9
    4. Track number of houses on each street
    5. Access number of houses as a combined key of Town and Street
    6. Street should be the primary key
    7. (Implied) how to loop through the streets and extract the other information

    Please correct the assumptions. Otherwise, solution goes something like this:

    #!/usr/bin/perl -w use strict; my %HouseInformation = (); { # Set up some information for testing $HouseInformation{6}{G} = 17; # 17 houses in Town G, Street +6 $HouseInformation{6}{A} = 9; # 9 houses in Town A, Street +6 $HouseInformation{8}{E} = 2; # 2 houses in Town E, Street +8 $HouseInformation{8}{K} = 8; # 8 houses in Town K, Street +8 $HouseInformation{9}{N} = 3; # 3 houses in Town N, Street +9 $HouseInformation{4}{J} = 7; # 7 houses in Town J, Street +4 # Loop through each street and get information foreach my $street (sort keys %HouseInformation) { foreach my $town (sort keys %{$HouseInformation{$street}}) { my $houseCount = $HouseInformation{$street}{$town}; print "Town $town, Street $street has $houseCount house +s.\n"; } } } exit;

    Results:

    C:\Steve\Projects\PerlMonks\TownStreetHouse>dir
     Volume in drive C is CBoot
     Volume Serial Number is B4AB-1A65
    
     Directory of C:\Steve\Projects\PerlMonks\TownStreetHouse
    
    05/16/2011  09:19 AM    <DIR>          .
    05/16/2011  09:19 AM    <DIR>          ..
    05/16/2011  09:19 AM               934 TownStreetHouse.pl
                   1 File(s)            934 bytes
                   2 Dir(s)   3,312,336,896 bytes free
    
    C:\Steve\Projects\PerlMonks\TownStreetHouse>perl TownStreetHouse.pl
    Town J, Street 4 has 7 houses.
    Town A, Street 6 has 9 houses.
    Town G, Street 6 has 17 houses.
    Town E, Street 8 has 2 houses.
    Town K, Street 8 has 8 houses.
    Town N, Street 9 has 3 houses.
    
    C:\Steve\Projects\PerlMonks\TownStreetHouse>
    

    Is that what you're looking for? As mentioned earlier, this is a Hash of Hashes (often abbreviated HoH or HOH). It may be helpful to think of it as a two-dimensional hash. Or as a two dimensional array where the index can be letters as well as numbers.

    Good luck.

Re: Please help, (perl hash)
by anonymized user 468275 (Curate) on May 16, 2011 at 14:09 UTC
    Normally the hash of hash as stated. But there is interestingly an array of array option for this very specific case where the towns and streets are nameless and have a contiguous identification system. For example
    $array[ ord( $town ) - 65 ][ $street - 1 ] = $houses;
    the expression involving ord converts the town letter into its corresponding position in the outer array and the inner array needs only the subtraction of one to map streets 1-9 to their array indexes in Perl.

    One world, one people

Re: Please help, (perl hash)
by thezip (Vicar) on May 16, 2011 at 18:32 UTC

    My apologies to those who have taken the time to provide their otherwise excellent answers.

    But really, since when have we resorted to completely answering somebody's obvious homework questions? In the past, we've requested that a user show a modicum of effort before we spill out the answer on the table. I didn't see that happen this time.

    Has our philosophy of "show your work first" changed?


    What can be asserted without proof can be dismissed without proof. - Christopher Hitchens

      The simple answer is: I answer how I am moved to answer.

      In this case, I don't think the homework question was completely answered, though several working examples of partial answers were provided.

      A mild irony is that after I posted mine (which was really only a summary of other peoples bits and pieces), I looked over the thread and only then realized that the OP hadn't actually posted any code. An odd moment, since I'm usually pretty quick with the "Show me what you've tried" angle.

      Nice Hitchens quote, by the way.

      FWIW, there are always those who want/need/do show off how smart they are -- if it answers a homework question, so be it -- here's hoping the teacher knows how to google :)
        > here's hoping the teacher knows how to google :)

        well ... I wouldn't be surprised if many of the usual suspects are teachers themselves.

        FWIW: I try to avoid reading threads entitled with "help", "please" and "urgent" (it's a good strategy for mental hygiene). But I don't care if others do...

        Cheers Rolf

Re: Please help, (perl hash)
by JavaFan (Canon) on May 16, 2011 at 13:08 UTC
    my %nr_of_houses; my $town = "G"; my $street = 6; $nr_of_houses{$town,$street} = 123; # 123 houses on street 6, in town + G. # Or $nr_of_houses{$town}{$street} = 123;
Re: Please help, (perl hash)
by sundialsvc4 (Abbot) on May 16, 2011 at 13:11 UTC

    The “value” of a hash-entry can be “a reference to” something else, e.g. another hash.   Furthermore, there can be more than one “reference to” the same piece of data, all of which lead to the same thing.   This gives you a very flexible way to create multi-dimensional structures.

    For instance, in your problem ... you have “towns” that refer to “streets” that refer to “houses.”   It really doesn’t matter that street-names are presently “1 to 9.”   (The city fathers might come up with a new scheme tomorrow night, and you don’t want that to break your code.)   The only requirement should be that the various names are unique within their respective “containers.”   (“Cherry” street in Maryvale, is not Cherry street in Lombard.)

    So, your Perl code might have constructions like this ...

    $map->{$town}->{$street}->{$house} ...

    Also note that any relational database structures that are used to populate these in-memory data structures do not have to have the same topology, and they frequently won’t.

Re: Please help, (perl hash)
by marinersk (Priest) on May 17, 2011 at 22:33 UTC

    Wow. Instead of posting a new question, you've edit and overwritten your old note with a new one.

    What gives?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://905064]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-19 07:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found