- Returns each element so deleted or the undefined value if there was no such element.
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.
So I decided to see whether deleting in array/list context would yield meaningful information in that respect. It doesn't:
my %a = (foo => undef); print "existed = ".(() = delete $a{foo})."\n"; print "notexisted = ".(() = delete $a{bar})."\n"; __END__ existed = 1 notexisted = 1
It seems that Perl is returning an array with the result of all possible deletions, so an array with the number of keys attempted to be deleted, not the actual number of keys deleted. Observe:
my %a = (foo => 1, bar => 2, baz => 3); $" = ','; print "existed = @{[delete $a{foo}]}\n"; print "notexisted = @{[delete @a{qw(foo bar baz)}]}\n"; __END__ existed = 1 notexisted = ,2,3
Anyway, that's what I learned today.
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.
Liz
Update:
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:
This is still a lot more than I would have hoped ;-( Especially if you have millions of keys.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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Deleting undef values from a hash
by Zaxo (Archbishop) on Dec 14, 2003 at 00:55 UTC | |
by liz (Monsignor) on Dec 15, 2003 at 09:46 UTC | |
Re: Deleting undef values from a hash
by ysth (Canon) on Dec 14, 2003 at 03:31 UTC | |
by tilly (Archbishop) on Dec 14, 2003 at 23:25 UTC | |
by ysth (Canon) on Dec 15, 2003 at 00:04 UTC | |
Re: Deleting undef values from a hash
by pg (Canon) on Dec 14, 2003 at 05:04 UTC | |
Re: Deleting undef values from a hash
by davido (Cardinal) on Dec 14, 2003 at 07:47 UTC |