in reply to How do I find the index of the last element in an array?

This node falls below the community's threshold of quality. You may see it by logging in.

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

    An observation:

    Juerd was just arguing against this syntax here today. I don't know what he means by: "$#foo + 1 isn't necessarily equal to @foo"(Some Perl array nuance I am not familiar with) but I tend to agree with him that using the more direct syntax:

    print "index of last element: $#A";

    is easier to understand and you don't have to leave future maintainers of your code guessing.

    Thanks

      I don't know what he means by: "$#foo + 1 isn't necessarily equal to @foo"(Some Perl array nuance I am not familiar with)

      $[ = 5; my @foo = qw(a b c); printf "Number of elements: %d\n", scalar @foo; printf "Last index: %d\n", $#foo; printf "*Number of elements: %d\n", $#foo + 1; printf "*Last index: %d\n", scalar @foo - 1;
      Number of elements: 3 Last index: 7 *Number of elements: 8 *Last index: 2
      One should of course NEVER set $[, but that is besides the point.

      Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

        Of course! Thanks for that answer Juerd! I'm willing to bet that "One should of course NEVER set $[" is exactly what the Camel book said too when I read about it so long ago.

        Thanks for the refresher.

      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.

        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