Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

merging two hashes

by sen (Hermit)
on Feb 08, 2006 at 20:48 UTC ( #528928=perlquestion: print w/ replies, xml ) Need Help??
sen has asked for the wisdom of the Perl Monks concerning the following question:

hell monks,

I need in my script, to merge the first element of each inner hash into array, but i didn't get the output what i need. i need the output as @a=(a g h i g h i)

my $s = { 'aa' => { '1' => ['a'], '2' => ['b','c','d'], '3' => ['f'], '4' => ['g'] }, 'bb' => { '1' => ['g','h','i'], '2' => ['s','a','d'] }, 'cc' => { '1' => ['g','h','i'], '2' => ['s','a','d'] } }; my @a= ($s->{aa}->{'1'},$s->{bb}->{'1'},$s->{cc}->{'1'}); print @a;

thanks in advance

Comment on merging two hashes
Download Code
Re: merging two hashes
by ikegami (Pope) on Feb 08, 2006 at 20:53 UTC

    While [ ... ] constructs an array, it returns a reference to the array, not the array itself. That means that $s->{aa}->{'1'} (for example) is a reference to an array. You need to dereference it.

    my @a = ( @{$s->{aa}->{'1'}}, @{$s->{bb}->{'1'}}, @{$s->{cc}->{'1'}}, );

    or (minimal change)

    my @a = map { @$_ } ( $s->{aa}->{'1'}, $s->{bb}->{'1'}, $s->{cc}->{'1'}, );

    or

    my @a = map { @{$s->{$_}->{'1'}} } keys %$s;
      If you're not going to sort the keys, you can just use values
      my @a = map @{$_->{1}}, values %$s;

      Caution: Contents may have been coded under pressure.
Re: merging two hashes
by jZed (Prior) on Feb 08, 2006 at 21:03 UTC
    my @a; for my $key(sort keys %$s){ push @a,$_ for @{$s->{$key}->{1}}; }
      That is an obsolete loop, jZed. Rather than: push @a, $_ for @b; I would write: push @a, @b;
Re: merging two hashes
by pKai (Priest) on Feb 08, 2006 at 21:42 UTC
    my @a = map { @{$s->{$_}->{'1'}} } sort keys %$s;

    Just combining the best (IMHO) of previous answers.

Re: merging two hashes
by trammell (Priest) on Feb 08, 2006 at 22:34 UTC

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2015-07-07 01:04 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 (86 votes), past polls