[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[MacPerl] foreach and referenced array



Hi. I am learning Perl (5), and in order to understand what's going on
with the references business, I was 'porting' a rather pointer-intensive
program I had written in Pascal long ago. I have been able to deal with
all the surprises, except one (until now...). Here is a toy version of
the problem code:
$numb = 20;

@stack = ([3,1,1,[]]);
&printstack;
$stack[0][3][2] += 5;
&printstack;
for ($i=0;$i<=$#{$stack[0][3]};$i++) {
  $stack[0][3][$i] *= $numb;
}
&printstack;

@stack = ([3,1,1,[]]);
&printstack;
$stack[0][3][2] += 5;
&printstack;
foreach $x (@{$stack[0][3]}) {
  $x *= $numb;
}
&printstack;

sub printstack {
  foreach $x (@stack) {
    print "\[$x->[0], $x->[1], $x->[2], \[",join(', ',@{$x->[3]}),"\]\]\n";
  }
}
I would have expected the same result from the two versions. But running
it, I get:
[3, 1, 1, []]
[3, 1, 1, [, , 5]]
[3, 1, 1, [0, 0, 100]]
[3, 1, 1, []]
[3, 1, 1, [, , 5]]
# Modification of a read-only value attempted.
File 'PB540 Alain:Documents:BH:Stat:Unitˇs:Test'; Line 17

I know that $x can only be used on the left of an assigment if the
second argument of the foreach is an array, and not an expression
returning an array value. Here, I have an array accessed by reference.
Any comments from the confirmed Perl gurus ? Thanks.

                                                    /AF