On Sun, Mar 09, 2014 at 04:40:54PM +1100, Alex Chiang wrote:
> Hi all, 
> 
> I'm a perl beginner, and when I tries to practice delete built-in, I
> find it's not working as I supposed to. 
> 
>  44   my %employ_list = ("e10220" => "Du", "e10250" => "Vic"); 
>  45   # iterate thru with each
>  46   while ( my ($k, $v) = each %employ_list ) {
>  47     print " before: key:$k => value:$v \n";
>  48     if ($k eq "e10220") { delete $employ_list{$k}; }
>  49     $employ_list{$k} = undef;
>  50     print "after: key:$k => value:$v \n";
>  51   }

> the delete built-in doesn't work, the output of print "after" is still
> the original dict.

That is because you are not printing out the value in the hash, you are
printing $v.  $v is not an alias to the hash value, it is a copy of the
original value in the hash.  $v doesn't change when you delete the value
from the hash.

On Sun, Mar 09, 2014 at 11:00:29AM +0200, Shlomi Fish wrote:

> In addition to what Uri said, you should not delete a key out of a hash (or
> add keys) while iterating over it using each(), because this may confuse Perl:

This is true in general, but the documentation explicitly states that it
is safe to use delete on the key most recently returned from each, as
Alex is doing here.  This is good because, as we see here, it can
reasonably be expected to work.

  perldoc -f each

-- 
Paul Johnson - p...@pjcj.net
http://www.pjcj.net

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to