Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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 HoH.pl 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://937613]
Approved by marto
help
Chatterbox?
[Happy-the-monk]: Moin !
[Discipulus]: good morning monks and nuns!
[Corion]: Hi Discipulus, Happy-the-monk!

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2018-07-23 08:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (459 votes). Check out past polls.

    Notices?