Crackers2 has asked for the wisdom of the Perl Monks concerning the following question:
I ran into some surprising (to me anyway) results with foreach and coderefs and list of constants. While investigating that I found a few more things that surprised me.
Let me start with the simplest case:
foreach my $x (0) { print $x++; }Which unsurprisingly gives a Modification of a read-only value attempted message.
Changing this just a little bit to have (0,1) instead of just (0) doesn't make a difference.
Changing it to (0..1) does work though, which was my first surprise. Apparently lists like this created internally by perl aren't read-only. Still, this probably isn't news to most monks.
Where things got really interesting for me was when adding coderefs into the mix. Again starting with a simple case, there's no surprises:
my $cl1 = sub { foreach my $x (0) { print $x++; } }; $cl1->(); $cl1->();
This, as expected, gives the read-only error.
Going to the equivalent of the second case...
my $cl2 = sub { foreach my $x (0..1) { print $x++; } }; $cl2->(); $cl2->();
does not show any new surprises. The output is
0101
Changing this just one bit more...
my $cl3 = sub { foreach my $x (0..1,5..6) { print $x++; } }; $cl3->(); $cl3->();
is where things get strange. Instead of my expected
01560156
output, I got
01561267
In other words, it appears that the 0..1,5..6 list was generated once when the sub was first called (or defined even?), and then reused
I'm not sure why this only happens if you combine several ranges.
Personally I'd consider the fact that lists generated from ranges aren't read-only a bug. Without this the other cases would just go away.
Does anyone know why this is happening?
Update: Removed "closures" from the title since as ikegami has shown they're irrelevant
Update2: Condense output a bit for easier viewing
Update3:
On ikegami's optimization remark, I want to add one more testcase:
for (1..2) { foreach my $x (0..1,5..6) { print $x++; } foreach my $x (0..1,5..6) { print $x++; } }
which shows that it does keep a different copy for both loops.
Update4: Retitled per Ieronim
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Unexpected behaviour with constant lists
by ikegami (Patriarch) on Jul 20, 2006 at 18:33 UTC | |
by Crackers2 (Parson) on Jul 20, 2006 at 18:42 UTC | |
by ikegami (Patriarch) on Jul 20, 2006 at 18:43 UTC | |
by diotalevi (Canon) on Jul 20, 2006 at 19:32 UTC | |
by ysth (Canon) on Jul 21, 2006 at 19:22 UTC | |
|
Re: Unexpected behaviour with constant lists and foreach (and closures?)
by davido (Cardinal) on Jul 20, 2006 at 18:42 UTC | |
by Crackers2 (Parson) on Jul 20, 2006 at 19:11 UTC | |
|
Re: Unexpected behaviour with constant lists and foreach (and closures?)
by Ieronim (Friar) on Jul 20, 2006 at 18:44 UTC |