Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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

Replies are listed 'Best First'.
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'}, );


    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 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 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 trammell (Priest) on Feb 08, 2006 at 22:34 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://528928]
Approved by ikegami
and the monastery is silent...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (1)
As of 2018-07-21 23:23 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (450 votes). Check out past polls.