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

Re: Hash arrays

by 2teez (Vicar)
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
$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

Replies are listed 'Best First'.
Re^2: Hash arrays
by BillKSmith (Vicar) on Dec 26, 2012 at 14:50 UTC
        push @{ $family_hash{$key} }, @values;

    I prefer

    $family_hash{$key} = [@values];
      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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1010344]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2018-05-27 20:24 GMT
Find Nodes?
    Voting Booth?