in reply to How & why does this work?

This works because of an optimisation to use the original array directly, when you're iterating over a single array. Otherwise, a list of the items to iterate over (referencing the original elements) is internally being created on the stack.  Try adding an empty list like this

foreach my $path (@all_paths, ()) {

and you'll notice that the "live-update" feature stops working.

That said, I'd like to point out that it's generally not a good idea to rely on such undocumented, implementation dependent behaviour. Also, even though it does work in this particular case, there are several other similar cases where modifying the array you're iterating over (with foreach) will produce unexpected behaviour...

Replies are listed 'Best First'.
Re^2: How & why does this work?
by kyle (Abbot) on Jul 11, 2008 at 14:07 UTC

    I agree. Instead of iterating over an array you modify this way, do it another way:

    while ( defined( my $path = shift @all_paths ) ) { # ...
    Update: ...but be aware that this leaves @all_paths empty.
Re^2: How & why does this work?
by Viki@Stag (Sexton) on Jul 11, 2008 at 14:17 UTC
      the $path (in my script's foreach) will be a reference (?)

      Not a reference in the normal Perl sense (i.e. you don't need to dereference it), but an alias to the original element (which at a lower level could be thought of as kind of a reference). In other words, modifying $path will modify the original value in the array. This applies in both cases, however (with and without optimisation), because the aliases are being set up to the individual elements, even when the intermediate list on the stack is being created.