Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Re: Deleting undef values from a hash

by Zaxo (Archbishop)
on Dec 14, 2003 at 00:55 UTC ( #314590=note: print w/replies, xml ) Need Help??

in reply to Deleting undef values from a hash

I agree that a documentation patch is the best response. Since the value for a key can be literally any scalar, it is impossible to think of a return value that would serve to distinguish between the two cases (at least without some perl magic).

We can imagine delete returning a hash or a list of key-value pairs, but (besides breaking compatibility) that would injure idioms that are more useful than knowledge of which keys existed before a deletion. The idiom for re-keying a value, $foo{'bar'} = delete $foo{'baz'}; would be wrecked, for instance.

A workaround can be devised pretty easily if we need the existence information, my @actual_values = delete @a{ grep { exists $a{$_}} @somekeys};
There are lots of variations possible on that snippet.

After Compline,

Replies are listed 'Best First'.
Re: Re: Deleting undef values from a hash
by liz (Monsignor) on Dec 15, 2003 at 09:46 UTC
    Rafael applied my documentation patch yesterday:
    -Returns each element so deleted or the undefined value if there was n +o such -element. Deleting from C<$ENV{}> modifies the environment. Deleting + from +Returns a list with the same number of elements as the number of elem +ents +for which deletion was B<attempted>. Each element of that list consi +sts of +either the value of the element deleted, or the undefined value. In +scalar +context, this means that you get the value of the last element delete +d (or +the undefined value if that element did not exist). + + %HASH = (foo => 11, bar => 22, baz => 33); + $scalar = delete $HASH{foo}; # $scalar is 11 + $scalar = delete @HASH{qw(foo bar)}; # $scalar is 22 + @array = delete @HASH{qw(foo bar baz)} # @array is (undef,undef +,33) + +Deleting from C<$ENV{}> modifies the environment. Deleting from a hash tied to a DBM file deletes the entry from the DBM file. Delet +ing from a C<tie>d hash or array may not necessarily return anything.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://314590]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2017-09-23 06:32 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (272 votes). Check out past polls.