Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Hash arrays

by 2teez (Priest)
on Dec 26, 2012 at 08:50 UTC ( #1010344=note: print w/ replies, xml ) Need Help??


in reply to Hash arrays

Something like this?:

use warnings; use strict; use Data::Dumper; my %family_hash; while (<DATA>) { my ( $key, @values ) = split /\s/, $_; push @{ $family_hash{$key} }, @values; } print Dumper \%family_hash; __DATA__ father male 65 Engineer mother female 60 home_engineering son male 28 musician daughter female 19 software_engineer
Output:
$VAR1 = { 'son' => [ 'male', '28', 'musician' ], 'daughter' => [ 'female', '19', 'software_engineer' ], 'father' => [ 'male', '65', 'Engineer' ], 'mother' => [ 'female', '60', 'home_engineering' ] };
You should see perldsc, HASHES-OF-ARRAYS

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me


Comment on Re: Hash arrays
Select or Download Code
Re^2: Hash arrays
by BillKSmith (Deacon) on Dec 26, 2012 at 14:50 UTC
        push @{ $family_hash{$key} }, @values;

    I prefer

    $family_hash{$key} = [@values];
    Bill
      Yes - that looks cleaner, but it is not the equivalent.

      Your code overwrites the contents of $family_hash{$key} while the OP's appends.
      So, if the $key appears more than once in the input data sequence, all but the last will be clobbered by your code.

                   "By three methods we may learn wisdom: First, by reflection, which is noblest; Second, by imitation, which is easiest; and third by experience, which is the bitterest."           -Confucius

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1010344]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2015-07-06 01:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (68 votes), past polls