in reply to Re^2: specific array in hash of arrays
in thread specific array in hash of arrays

Though looking up a hash will often be better than doing a linear search along a list. For example:

#!/usr/bin/perl use strict; use warnings; my %hoh = ( flasha => { dd1 => 1, dd2 => 2, dd3 => 3, dd4 => 4 }, flashb => { gg1 => 1, gg2 => 2, gg3 => 3, gg4 => 4 }, flashc => { cc1 => 1, cc2 => 2, cc3 => 3, cc4 => 4 }, ); for ([qw(flasha dd4)], [qw(glashz gg2)], [qw(flashc zz)], [qw(flashc c +c1)]) { my ($array_name, $to_find) = @$_ ; if (exists $hoh{$array_name}->{$to_find}) { print( "$array_name contains $to_find\n" ); } }
noting that exists stops looking, without complaint, if $hoh{$array_name} doesn't exist.

If the list is a trivial length, then List::Util::first at least stops looking when it gets a match.

I don't know what you need to do having discovered the match... the above allows you to map "array name" and "to_find" to anything you like -- the numbers above are for illustration, only !

If you're only interested in existence, then

flasha => { map { ($_, undef) } qw(dd1 dd2 dd3 dd4) },
will serve.

Replies are listed 'Best First'.
Re^4: specific array in hash of arrays
by ikegami (Patriarch) on Oct 09, 2008 at 14:11 UTC
    if (exists $hoh{$array_name}->{$to_find}) {
    should normally be
    if ( exists( $hoh{$array_name} ) && exists( $hoh{$array_name}->{$to_find} ) ) {

    to prevent autovivification of entries into %hoh. That might not matter here, though.

      Rats... "autovivication" :-(

      Just when I thought I was getting to grips with Perl magic, another piece bites me in the backside... "autovivifying" an rvalue ? ...of course, silly me !

        lvalue or rvalue doesn't matter. Treating an undefined variable as a reference will instantiate the referree and store a reference in the variable.

        Note that it's -> performing the autovivification, not exists.