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

I seek the wisdom of the monks. I have an array of hashes such as:
@AoH = ( { husband => "barney", wife => "betty", son => "bamm bamm", }, { husband => "george", wife => "jane", son => "elroy", }, { husband => "homer", wife => "marge", son => "bart", }, );
Is it possible without using a loop to assign all the values for one key of all the hashes to an array?

Something along the lines of:
@husbands = @AoH->{husband};

so @husbands contains ("barney", "george", "homer")

Cheers
Weevil

Replies are listed 'Best First'.
Re: Get AoH values into array
by FunkyMonk (Bishop) on Sep 06, 2007 at 18:07 UTC
    my @husbands = map { $_->{husband} } @AoH;

    See map for more info

      This may be a newbish question, but according to the map perldoc...
      %hash = map { getkey($_) => $_ } @array; is just a funny way to write %hash = (); foreach $_ (@array) { $hash{getkey($_)} = $_; }
      So doesn't map still solve the problem by using a loop? And wouldn't all the inefficiencies of using a loop directly be carried over by using map?

      Honest questions, I'm genuinely curious.

        Unless you want a recursive solution, there will be a loop, either explicity with for, while etc, or implicitly with map, grep etc.

        Some people (but not me) might prefer something like:

        my @husbands = husbands( @AoH ); sub husbands { my $this = shift; return ( $this->{husband}, husbands( @_ ) ) if @_; return $this->{husband}; }

        Look Ma, no loops!

Re: Get AoH values into array
by throop (Chaplain) on Sep 07, 2007 at 02:36 UTC
    Loops solve in linear time with the number of elements tested. Generally, you don't need to worry about the inefficiencies of single loops, unless you are processing huge data sets.

    Worry about loop inefficiencies when you have loops inside loops and your solution time is quadratic (N2).

    Or worse.

    throop

      Thank you monks

      I'm not worried about the inefficiency of loops, my data set is not large. It was just that once I learned that I can put 2 arrays into a hash like this

      my %h; @h{@a}=@b;
      I sort of hoped there were other loop avoiding constructs to learn.. Loops are so c.

      Cheers
      Weevil