in reply to Getting at a hash from its values

Here's one way of doing what you're asking for. Note that if you try to get an index for a child_fh value that does not exist, this method will die() on you (purposely).

my @hashes = ( { child_fh => $obj1 }, { child_fh => $obj2 } ); my @readable = $s->can_read(1); for (@readable) { my $index = -1; while (++$index > -1) { last if ($hashes[$index]{child_fh} == $_); die("object not found in $hashes!\n") if ($index == $#hashes); ); # $index now contains your array index, '3' or '5' # from your example. print $hashes[$index]{child_fh}, "\n"; }

Replies are listed 'Best First'.
Re^2: Getting at a hash from its values
by ikegami (Patriarch) on Mar 01, 2006 at 05:54 UTC
    The following two snippets are a bit easier to read:
    my @readable = $s->can_read(1); for my $fh (@readable) { my ($index) = grep { $hashes[$_]{child_fh} == $fh } 0..$#hashes; die("object not found in \$hashes!\n") if not defined $index; ... }

    and

    use List::Util qw( first ); my @readable = $s->can_read(1); for my $fh (@readable) { my $index = first { $hashes[$_]{child_fh} == $fh } 0..$#hashes; die("object not found in \$hashes!\n") if not defined $index; ... }
    Or if you don't need the index, just the object in @hashes:
    my @readable = $s->can_read(1); for my $fh (@readable) { my ($obj) = grep { $_->{child_fh} == $fh } @hashes or die("object not found in \$hashes!\n"); ... }

    and

    use List::Util qw( first ); my @readable = $s->can_read(1); for my $fh (@readable) { my $obj = first { $_->{child_fh} == $fh } @hashes or die("object not found in \$hashes!\n"); ... }