FAQ 4.57 What happens if I add or remove keys from a hash while iterating over it?

Discussion in 'Perl Misc' started by PerlFAQ Server, Jan 10, 2011.

  1. This is an excerpt from the latest version perlfaq4.pod, which
    comes with the standard Perl distribution. These postings aim to
    reduce the number of repeated questions as well as allow the community
    to review and update the answers. The latest version of the complete
    perlfaq is at http://faq.perl.org .

    --------------------------------------------------------------------

    4.57: What happens if I add or remove keys from a hash while iterating over it?

    (contributed by brian d foy)

    The easy answer is "Don't do that!"

    If you iterate through the hash with each(), you can delete the key most
    recently returned without worrying about it. If you delete or add other
    keys, the iterator may skip or double up on them since perl may
    rearrange the hash table. See the entry for "each()" in perlfunc.



    --------------------------------------------------------------------

    The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
    are not necessarily experts in every domain where Perl might show up,
    so please include as much information as possible and relevant in any
    corrections. The perlfaq-workers also don't have access to every
    operating system or platform, so please include relevant details for
    corrections to examples that do not work on particular platforms.
    Working code is greatly appreciated.

    If you'd like to help maintain the perlfaq, see the details in
    perlfaq.pod.
     
    PerlFAQ Server, Jan 10, 2011
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. NM
    Replies:
    6
    Views:
    491
    Default User
    Sep 20, 2006
  2. Neal Becker
    Replies:
    1
    Views:
    246
    Alex Martelli
    Sep 2, 2007
  3. rp
    Replies:
    1
    Views:
    561
    red floyd
    Nov 10, 2011
  4. Steven Hirsch

    Iterating over a hash of hash of hashes

    Steven Hirsch, Aug 19, 2008, in forum: Ruby
    Replies:
    0
    Views:
    159
    Steven Hirsch
    Aug 19, 2008
  5. limitz

    Iterating over a hash

    limitz, Jul 6, 2007, in forum: Perl Misc
    Replies:
    8
    Views:
    132
    limitz
    Jul 10, 2007
Loading...

Share This Page