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

Re: [MacPerl] Unexpected Splice behavior?



> 
> The following code produces the unexpected results. When it is run as
> written, it prints 2 3 4 as opposed to the expected 3 4. When the < sign in
> the if line is changed to >, it prints 1 2 3 as expected. How come? A
> possible bug in Perl or MacPerl?

Nope.  It's doing the right thing.

You're shifting the base of @ary on the first loop through to 
the 1st element, which has the value of 2.  Then, on the next 
loop, $i gets incremented to 1, and $ary[$i] is now the value, 3.  
The test is only true on the first pass.  splice() is kinda
tricky sometimes.  You might think that if you change the test to

	if ($ary[$i] <= 3) {

you'd get the right result, but then you wind up shifting the
1st element (3) on the second pass, and you get 2 4.
shift() does what you want in that case.

Bill


> @a = (1,2,3);
> append(*a);
> 
> sub append {
>    local(*ary) = @_;
>    push (@ary, 4);
>    for ($i = 0; $i < @ary; $i++) {
>       if ($ary[$i] < 3) {
>          splice(@ary, $i, 1);
>        }
>    }
> }
> 
> print "@a\n";