in reply to foreach loop question

Why the following code does not process elements added inside the loop ...

Consider that

foreach ( sort keys %h ) { ... $h{$new} = $new;
is equivalent to
@sorted = sort keys %h; foreach ( @sorted ) { ... $h{$new} = $new;
The keys have been extracted from the hash before being sorted and processed. Any keys you add after that aren't "visible" to the foreach.

By the way, the "next;" is redundant.

Replies are listed 'Best First'.
Re: Re: foreach loop question
by dda (Friar) on Apr 16, 2003 at 18:45 UTC
    Well, thanks. But without "sort" it works the same way. I wonder how it processes large arrays - always creates a copy?

    --dda

      Well, thanks. But without "sort" it works the same way.

      I should have been more explicit. It's "keys" that creates the new array, not the sort.

      If you want to process all of the keys and values in a hash without creating a new array to hold the hash keys, look into "each".

      while ( ($key, $value) = each %h ) { ...
      This doesn't create an additional array. Note, though, that it's unsafe to manipulate the hash while you're iterating over it. The proviso in the docs reads:
      If you add or delete elements of a hash while you’re iterating over it, you may get entries skipped or duplicated, so don’t. Exception: It is always safe to delete the item most recently returned by "each()".