Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Testing if a HoH key exists

by Jeri (Scribe)
on Nov 11, 2011 at 16:45 UTC ( #937613=perlquestion: print w/replies, xml ) Need Help??
Jeri has asked for the wisdom of the Perl Monks concerning the following question:

Hi! I'm trying to see if a nested Hash key exists. If it does, I want to delete it. Here's what I've written.

if (exists %{$rHoH_ProteinFamilies->{$proteinfamily}->{$PROTEIN}}) { delete $rHoH_ProteinFamilies->{$proteinfamily}->{$PROTEIN}; }

Here's the error.

exists argument is not a HASH or ARRAY element or a subroutine at line 123.

Thanks in advance!

Replies are listed 'Best First'.
Re: Testing if a HoH key exists
by johnny_carlos (Scribe) on Nov 11, 2011 at 16:56 UTC
    I think it's because you are dereferencing your hash, so it is no longer a key, but a value. Try just:

    exists $rHoH_ProteinFamilies->{$proteinfamily}->{$PROTEIN}

      That worked! Thanks. Before I was iterating through the hash using a for loop and forgot that I was still using an entire hash and not a element.
Re: Testing if a HoH key exists
by chilledham (Friar) on Nov 11, 2011 at 16:56 UTC

    exists works on single elements of a hash (or array), not an entire hash (or array). (Monks, is is appropriate to say exists works in scalar context?) If you remove the % sigil and first set of curlies (leaving  if (exists $rHoH_ProteinFamilies->{$proteinfamily}->{$PROTEIN}) Your error should go away.

    See perldoc -f exists

Re: Testing if a HoH key exists
by hbm (Hermit) on Nov 11, 2011 at 17:19 UTC

    You can just delete the key without testing, unless you plan to do something else in that 'if' block.

      What if the key doesn't exist? Will it throw an error? (I would test it but my data is convoluted)

        It will not throw an error. Try simply,

        perl -e 'use strict; use warnings; my %H; delete $H{jeri}'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://937613]
Approved by marto
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2018-04-20 11:10 GMT
Find Nodes?
    Voting Booth?