<?xml version="1.0" encoding="windows-1252"?>
<node id="314585" title="Deleting undef values from a hash" created="2003-12-13 19:29:43" updated="2005-07-07 15:05:33">
<type id="120">
perlmeditation</type>
<author id="272239">
liz</author>
<data>
<field name="doctext">
&lt;I&gt;perldoc -f delete&lt;/I&gt; states:
&lt;DL&gt;&lt;DD&gt;
Returns each element so deleted or the undefined value if there
was no such element.
&lt;/DL&gt;
Which is of course nice, because it gives you a way to find out whether a key was really deleted from the hash.  Or does it?
&lt;P&gt;
If the value associated with the key in the hash was undef, then being returned undef doesn't tell you anything.  The undef could be from the hash, it could also be supplied Perl to "indicate" nothing was deleted from the hash.
&lt;P&gt;
So I decided to see whether deleting in array/list context would yield meaningful information in that respect.  It doesn't:
&lt;code&gt;
my %a = (foo =&gt; undef);
print "existed = ".(() = delete $a{foo})."\n";
print "notexisted = ".(() = delete $a{bar})."\n";
__END__
existed = 1
notexisted = 1
&lt;/code&gt;
&lt;P&gt;
It seems that Perl is returning an array with the result of all possible deletions, so an array with the number of keys &lt;B&gt;attempted&lt;/B&gt; to be deleted, not the actual number of keys deleted.  Observe:
&lt;P&gt;
&lt;code&gt;
my %a = (foo =&gt; 1, bar =&gt; 2, baz =&gt; 3);
$" = ',';
print "existed = @{[delete $a{foo}]}\n";
print "notexisted = @{[delete @a{qw(foo bar baz)}]}\n";
__END__
existed = 1
notexisted = ,2,3
&lt;/code&gt;
&lt;P&gt;
Anyway, that's what I learned today.
&lt;P&gt;
Since this behaviour goes back to at least Perl 5.00503, I think I'll provide a documentation patch, so that at least I will understand this the next time I read it.
&lt;P&gt;
Liz
&lt;P&gt;
&lt;B&gt;Update&lt;/B&gt;:&lt;BR&gt;
Just to be clear: I knew about exists()  ;-)  My reason for using undef as a value in the hash, is that it uses less memory than a defined value:
&lt;code&gt;
use Devel::Size qw(size total_size);

$a{1} = undef;
$b{1} = 0;
$c{1} = 1;
$d{1} = 10;
$e{1} = 'abcd';

print "$_: ".(total_size( \%{$_} ) - size( \%{$_} ))."\n" for a..e;
__END__
a: 12
b: 16
c: 16
d: 16
e: 29
&lt;/code&gt;
This is still a lot more than I would have hoped  ;-(   Especially if you have millions of keys.</field>
</data>
</node>
