in reply to Hashes: Deleting elements while iterating

foreach $key (%index){ #foreach $key (sort keys %index){
Why do you have the correct line commented out? You will iterate over keys and values using this.

Replies are listed 'Best First'.
Re: Re: Hashes: Deleting elements while iterating
by knexus (Hermit) on Sep 02, 2003 at 20:55 UTC
    Sorry, maybe I wasn't clear... or maybe I just chose poorly in the code.

    What I did was put 3 different ways of iterating over the hash when deleting. To test the different ones I would just COMMENT OUT the others and do a quick run.

    If I USE the first one I get errors. If I use the last 2 (the foreach w/ sort and the while) they work and no errors.

      Put in a print statement in the "faulty" for-loop and you'll see immediately what goes wrong.

      foreach $key (%index){ print "deleting $key\n"; # delete $index{$key} if ($key =~ /$test.+/); }

      Hope this helps, -gjb-

        Yes, indeed it does help. Thanks.

        So, after digging more in my book, I see now that i needed a keys function in it. All is well again.

        foreach $key (keys %index) { print "deleting $key\n"; # delete $index{$key} if ($key =~ /$test.+/); }

        Some of us just need learn the hard way!

        Update: I see now an earlier reply by chromatic, mentioned needing the keys function as well, but it was lost on me at that moment. Sorry.