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

I have a hash I am trying to sort. However, I am trying to sort it by deeper values than has been discussed on the monastery before. (I spent a good hour in the Super Search). So here's some test code:
my %HoH = ( 1 => +{ foo => 'bar', baz => 'bletch', }, 2 => +{ foo => 'bar2', baz => 'bletch2', }, ); my @fookeys; # select 'foo' from 'HoH' where 'foo' = 'bar2' @fookeys = sort { $HoH{$a} -> {foo} eq 'bar2' } keys %HoH; use Data::Dumper; # fookeys is [ 1, 2 ] print Dumper \@fookeys; # try again @fookeys = sort { $HoH{$a}{foo} eq 'bar2' } keys %HoH; # fookeys is [ 1, 2 ] print Dumper \@fookeys;
I want every key from HoH where $HoH -> {foo} eq 'bar2'. Seems to me that sort would work. Im actually pretty curious what it thinks im asking it to do. Can anyone shed some light on this?

Thanks,
brother dep.

--
Laziness, Impatience, Hubris, and Generosity.

Replies are listed 'Best First'.
(ar0n) Re: Using 'sort' to emulate SQL's 'select'...
by ar0n (Priest) on Apr 22, 2001 at 19:41 UTC
    Why are you using a sort to get the keys? And why the pluses? Pluses are usually used to distinguish between a block of code and a hash, but in this case you don't need the '+' because it'll be considered an anonymous hash anyways...

    my %HoH = ( 1 => { foo => 'bar', baz => 'bletch' }, 2 => { foo => 'bar2', baz => 'bletch2' }, ); my @fookeys = grep { $HoH{$_}{foo} eq 'bar2' } keys %HoH; # @fookeys is now 2


    ar0n ]

      from perldoc perlref:
      For example, if you wanted a function to make a new hash and return a reference to it, you have these options: sub hashem { { @_ } } # silently wrong sub hashem { +{ @_ } } # ok sub hashem { return { @_ } } # ok On the other hand, if you want the other meaning, you can do this: sub showem { { @_ } } # ambiguous (currently o +k, but may change) sub showem { {; @_ } } # ok sub showem { { return @_ } } # ok The leading +{ and {; always serve to disambiguate the expression to mean either the HASH reference, or the BLOCK.
      I use HoH's a lot in my code, so I try to make absolutely sure my hashes are as disambiguated as they can be.

      --
      Laziness, Impatience, Hubris, and Generosity.

Re: Using 'sort' to emulate SQL's 'select'...
by lucs (Sexton) on Apr 22, 2001 at 21:35 UTC
    Actually, I think you want grep():
    @fookeys = grep $HoH{$_}{foo} eq 'bar2', keys %HoH; print "@fookeys\n"; # Only `2' is there.

    By the way, your usage of sort() is wrong. The comparison function used by sort() must involve both $a and $b, else sort() cannot do its job properly.

    Also, you should realize that sort() will return a copy of _all_ the elements you ask it to sort; that's why you want grep().