in reply to Getting the next array element while still keeping the current one

You're very close. The post-increment operator (as in $i++) returns the current value and then increments the value, while the pre-increment operator (as in ++$i), increments the value immediately and returns the incremented value.

In this case, however, I don't think you even want that, as it will mess up your counter. All you really want is $i + 1 (untested code follows, note that this will mess up on the last output, since nothing follows 'betty'):

my @array = qw( wilma fred barney betty ); for my $i (0 .. $#array) { printf( "We have %s, while %s is next.", $array[$i], $array[$i + 1] ); }

Replies are listed 'Best First'.
Re: Getting the next array element while still keeping the current one
by Anonymous Monk on May 01, 2004 at 20:33 UTC
    What if my array contains numbers. When I try to use $array[$i+1] -  $array[$i] I get use of uninitialized value in subraction.
      When I try to use $array[$i+1] -  $array[$i] I get use of uninitialized value in subraction.

      This is probably a sign that you run $i across all valid indexes in your array -- which means that $i + 1 will be one past the end of the array, and thus uninitialized. If you are looking for adjacent differences, try this:

      my @array = ( ... ); my @adj_diff; for ( my $i = 0; $i < $#array; ++$i ) { push @adj_diff, $array[$i+1] - $array[$i]; }

      This should result in @adj_diff having one fewer elements than @array. If you like the functional mode of programming, you could do it with a map too:

      my @adj_diff = map { $array[$_+1] - $array[$_] } 0 .. $#array-1;

        The loop:

        for ( my $i = 0; $i < $#array; ++$i )
        may be slightly too subtle, since we often have loops that look like:
        for ( my $i = 0; $i <= $#array; ++$i )
        or:
        for ( my $i = 0; $i < @array; ++$i )
        and it would be easy for the eye to pass over that and miss the difference.

        I'd be tempted to write it instead as:

        for ( my $i = 0; $i <= $#array - 1; ++$i )
        to emphasise the departure from the common idiom.

        Hugo