Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

'undef'ing a hash element

by Deda (Novice)
on Aug 26, 2003 at 12:09 UTC ( [id://286666] : perlquestion . print w/replies, xml ) Need Help??

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

hi, i have a hash like
%hash=( a => 1 b => 2 }
How do I 'undef' a hash entry - not the value, but the key? if i write
undef $hash{a}
i get
%hash=( a => undef b => 2 }
What i want to get is
%hash=( b => 2 }
I need this for %ENV modification (UX: unset equivalent).

Replies are listed 'Best First'.
Re: 'undef'ing a hash element
by antirice (Priest) on Aug 26, 2003 at 12:13 UTC

    I believe delete is what you're looking for.

    Hope this helps.

    The first rule of Perl club is - use Perl
    ith rule of Perl club is - follow rule i - 1 for i > 1

      This is exactly what I was looking for. thx
Re: 'undef'ing a hash element
by arthas (Hermit) on Aug 26, 2003 at 12:17 UTC


    You should use:

    delete $hash{$a}

    This removes the key/value pair. undef only sets the key's value to the undefined value.


      This is a little off-topic, but you may find the info useful in the long run. For fun, check out Hash::NoVivify to learn about a related subtlety of hash key management and a module for dealing with it.