hsinclai has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I'm seeing wierd behavior in this snippet - and can't understand why..

use strict; use warnings; my @lines = qx!cat /etc/services!; my @range = '1' .. $#lines; my @blah; push( @blah, $lines[ $#lines - splice( @range, int rand @range, 1 ) ] +) for @range; print $#blah . $/;
Whatever number of elements @range contains, $#blah always contains half that number, minus 1.

Replacing the qx!cat .. ! with open and getting the file contents into an array doesn't change the behavior... Replacing the "int rand" with a plain number, or POSIX floor/ceil doesn't change the behavior..

Using a more standard

for ( @range ) { push( @blah, $lines[ $#lines - splice( @range, int rand @range, 1 ) + ] ) }
seems to have no effect either..

Can anyone see why this happens? (my /etc/services file has 9252 lines, same effect with other files)

Is it a bad idea to put code in between the brackets of $array[indices] ?

Many thanks for your insight!

Replies are listed 'Best First'.
Re: possible wierdness from "for @array"
by moritz (Cardinal) on Mar 31, 2009 at 16:53 UTC
    push( @blah, $lines[ $#lines - splice( @range, int rand @range, 1 ) ] )

    You are deleting items from an array you are iterating over, before or after the cursor. That's going to cause trouble. Don't do that.

Re: possible wierdness from "for @array"
by ikegami (Patriarch) on Mar 31, 2009 at 16:56 UTC

    Your loop is ending prematurely because you are modifying the array over which you are iterating.

    You also have an off by one error.
    my @range = '1' .. $#lines;
    should be
    my @range = 0 .. $#lines;

    The "$#lines -" is pointless.
    $lines[ $#lines - splice(...) ]
    can be replaced.
    $lines[ splice(...) ]

    Finally, the use of splice can be replaced with a more efficient swap and pop.

    Or you could just use shuffle from List::Util.
    my @blah = shuffle @lines;

Re: possible wierdness from "for @array"
by CountZero (Bishop) on Mar 31, 2009 at 20:29 UTC
    perldoc perlsyn has the following:
    If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James