On 03/09/2014 05:00 AM, Shlomi Fish wrote:
Hi Alex,

On Sun, 9 Mar 2014 16:40:54 +1100
Alex Chiang <s3442...@student.rmit.edu.au> 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}; }

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:

http://perl-begin.org/tutorials/bad-elements/#modifying_iterated_array

that is wrong for delete on the most recent key returned from each (from perldoc -f each):

If you add or delete
               a hash's elements while iterating over it, entries may be
               skipped or duplicated--so don't do that.  Exception: It is
               always safe to delete the item most recently returned by
               "each()", so the following code works properly:

                       while (($key, $value) = each %hash) {
                         print $key, "\n";
                         delete $hash{$key};   # This is safe
                       }

that is what was being done in the OP's code.

uri

--
Uri Guttman - The Perl Hunter
The Best Perl Jobs, The Best Perl Hackers
http://PerlHunter.com

--
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