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

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;

Replies are listed 'Best First'.
Re: Re^2: Getting the next array element while still keeping the current one
by hv (Prior) on May 02, 2004 at 12:28 UTC

    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

      it would be easy for the eye to pass over that and miss the difference

      I agree a little, but at some point I'm willing to trust the programmer to be a bit more aware. (Also, this is the sort of thing that I would try to shove off into a library, so I can think about it as a chunk instead of in detail.)

      Of the various permutations which might make it more obvious, I'm torn between an actual comment (since, if we don't trust the programmer to read code accurately, is there any point to putting a subtle clue to a subtle difference into the code at all?) or by using the @array - 1 form. So, let's do both:

      # loop over all but last element for ( my $i = 0; $i < @array - 1; ++$i )

      But this probably just reflects my history with c-style loops (and their tendency to use the less-than operator, instead of the less-than-or-equals...). I wonder if writing it as a foreach is any more self-documenting:

      # loop over all but last element foreach my $i ( 0 .. $#array-1 )

      Thanks for the feedback, though. :)