let's pretend there's an awful lot of them, or the hash is tied, and it's harder to find an existing key than fetch a value

Well, a pretty foolproof method is to build an array of keys to delete, and delete them later. But by what you said I am guessing this list might grow very long, so that might not be feasible?

LanX has a point that resetting the iterator on each loop might result in an endless loop if one is not careful. But I think that resetting the iterator only when keys are actually deleted might be an option, e.g.:

use warnings; use strict; use Data::Dump qw/ dd pp /; my %h = ( 1 => [2..7], 8 => [ 9 ], 9 => [ 8 ], (map { $_ => [ 1 ] } 2..7), ); dd \%h; while ( my ($k,$v) = each %h ) { print "Loop from ",pp($k)," -> ",pp($v),"\n"; rec_delete( \%h, $k ); } dd \%h; sub rec_delete { my ($hash, $key) = @_; return unless exists $hash->{$key}; my $value = delete $hash->{$key}; keys %$hash; return unless $value; print "Recursing ",pp($key)," -> ",pp($value),"\n"; rec_delete( $hash, $_ ) for @$value; }

In reply to Re: Iterating over an hash while removing keys by haukex
in thread Iterating over an hash while removing keys by Eily

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.