in reply to Re: Answer: How do I find the index of the last element in an array?
in thread How do I find the index of the last element in an array?

If foo is an empty, or undefined, array, then @foo is undef, but $#foo is -1.

In such a case, $#foo does equal scalar(@foo)-1, but scalar(@foo) does not equal $#foo+1.

--
Tommy
Too stupid to live.
Too stubborn to die.

Replies are listed 'Best First'.
Re: Re: Re: Answer: How do I find the index of the last element in an array?
by edan (Curate) on Jun 02, 2003 at 14:41 UTC

    No, I don't think so. If @foo is empty, then scalar(@foo) is zero, not undef, and the equality holds true... (actually undef == 0 is also true, though it emits a warning)

    The only time @foo != $#foo + 1 is when you messed with $[ (but you didn't do that, did you?)

    --
    3dan

      Ack. Damn those non-scalar contexts!

      perl -e 'print $#a, "\n", @a, "\n", $#a+1, "\n"' -1 0
      Thus clearly showing that @a is undef. Which is true. In a list context...

      If I'd remembered to include scalar around it:

      perl -e 'print $#a, "\n", scalar (@a), "\n", $#a+1, "\n"' -1 0 0
      , I'd have got the right answer...

      My bad.

      --
      Tommy
      Too stupid to live.
      Too stubborn to die.