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

Re: [MacPerl] foreach and referenced array



>I think the problem is that the first two elements of the inside array are
>undefined.  If there is already a value in the array slot, the foreach
>provides $x that is an lvalue--your not changing where the value is
>stored, just the value.  However, if the array slot is undefined, it will
>try to allocate space for the value, which would require updating
>that slot's pointer to point to the newly allocated space.  However, the
>foreach is only working with a local copy of the 'pointer' and thus
>cannot change it (it's 'read-only' as it complained) to go from undefined
>to defined.
>
>I don't know if that made sense...

Yes it did... I just verified that the same problem happens with a
straight (I mean not 'pointed at') array. So, foreach may be used to
modify the value of the elements of an array, but not to call them
into existence. Which I find surprising. After all, if you replace a
value with something longer, would it not need to find some other place
in memory to store that longer value, and then update the pointer in the
array slot to point to that new place ? (I suppose you used the term
'pointer' to talk about the pointers used internally by the interpreter).
But wait a minute... Let's try this:
$numb = 20;
@stack = ();
$stack[0] += 1;
$stack[2] += 3;
foreach $x (@stack) {
  print "$x  ";
  $x *= numb;
  print "$x\n";
}

with MacPerl 4, we get:
1  5
  0
3  15

with MacPerl 5, we get:
1  0
# Modification of a read-only value attempted.
File 'PB540 Alain:Documents:BH:Stat:Unitˇs:Test2'; Line 8

Mmmm. I prefer what MacMerl 4 does here.

                                                    /AF