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

I am try to grep for a element in an array that is a member of a hash. Something like this:
my %H1 = { 'THINGS' => ['thing1', 'thing2'], 'PEOPLE' => ['andy', 'margot', 'dave', 'joe'], }; ... my $thing = 'thing1'; deleteFromH1 ( $user ) if grep ($thing, @{$H1{'THINGS'}} );
But my sub deleteFromH1 never gets called because I guess the grep is not finding $thing in the hash. What am I doing wrong here? Thanks

Replies are listed 'Best First'.
Re: Hash-O-Array Help
by ccn (Vicar) on Oct 29, 2008 at 23:25 UTC

    Use parens instead of curly braces when defining a hash

    my %H1 = ( 'THINGS' => ['thing1', 'thing2'], 'PEOPLE' => ['andy', 'margot', 'dave', 'joe'], );
      Thanks ccn. Now if I wanted to delete 'dave' I could do ...
      delete @{$H1{'PEOPLE'}}[2];
      ... but that leaves my hash looking like this ...
      $VAR1 = 'PEOPLE'; $VAR2 = [ 'andy', 'margot', undef, 'joe' ]; $VAR3 = 'THINGS'; $VAR4 = [ 'thing1', 'thing2' ];
      How can I free up that 'undef' array element ? Thanks
Re: Hash-O-Array Help
by ikegami (Patriarch) on Oct 30, 2008 at 00:24 UTC

    { ... } creates a hash initializes it with the contents of the braces, and returns a reference to the hash. It makes no sense to assign that to a hash variable.

    When you use parens instead of curlies, it builds a list. When a list is assigned to a hash variable, it's treated as a sequence of key-value pairs. In the code you presented, there's only one value in the list (a reference to a hash), so it's treated as a key after issuing a warning.

    That explains the problem you were already told about. You have a second problem, though.
    grep($thing, @{...})
    means
    grep { $thing } @{...}
    Since $thing has a true value, that's the same as just
    @{...}
    You probably want to use
    grep($_ eq $thing, ...)

Re: Hash-O-Array Help
by toolic (Bishop) on Oct 29, 2008 at 23:40 UTC
    You probably also want to check using eq:
    use strict; use warnings; my %H1 = ( 'THINGS' => ['thing1', 'thing2'], 'PEOPLE' => ['andy', 'margot', 'dave', 'joe'], ); my $thing = 'thing1'; if (grep {$_ eq $thing} @{$H1{'THINGS'}}) { print "found\n"; } else { print "not found\n"; }
Re: Hash-O-Array Help
by GrandFather (Saint) on Oct 29, 2008 at 23:46 UTC