in reply to Re^2: Initialization of arrays
in thread Initialization of arrays

For times when I access the last element of an array, I use @array[-1]; however, when I need to know the value of the last index, such as in a loop above, I have seen people recommend two approaches. Let's use the for snippet from the above -- it could be written in either of:

for my $y (0..@x-1) { } # or # for my $y (0..$#x) { }

Is there a practical difference?

<-radiant.matrix->
Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
The Code that can be seen is not the true Code
"In any sufficiently large group of people, most are idiots" - Kaa's Law

Replies are listed 'Best First'.
Re: (digression) preferred syntax for index of last array element?
by ikegami (Patriarch) on Sep 22, 2005 at 14:39 UTC

    There might be an extra op in the @x-1 version, but using the latter because of this would be "premature optimization". Pick whichever one you prefer. Personally, I prefer beating around the bush and use last ($#x) if I mean last, and count (@x) if I mean count. The down side is that the reader must be familiar with both ops.

    But that's assuming (deprecated) $[ is left untouched.. If $[ is 1, they're both wrong. The solution for $[ = 1 is
    for my $y (1..$#x) { }
    or
    for my $y (1..@x) { }
    and the general solution is
    for my $y ($[..$#x) { }
    or
    for my $y ($[..$[+@x-1) { }

      If you don't want to mess with $[, install a recent version of perl, where $[ has a lexical effect, like the integer, locale, warning, strict pragmas. (That could still cause problems if someone depends heavily on the old behaiviour of $[.)