in reply to Re: Perl Array - What an array contains
in thread Perl Array - What an array contains

Watch out, though. $#capitals would evaluate to true (-1) if the list has no capitals:

perl -lE "@capitals=(); $,=', '; print scalar(@capitals), $#capitals, +$#capitals ? 'Lots' : 'One'; 0, -1, Lots perl -lE "@capitals=qw(London); $,=', '; print scalar(@capitals), $#ca +pitals, $#capitals ? 'Lots' : 'One'; 1, 0, One perl -lE "@capitals=qw(London Paris); $,=', '; print scalar(@capitals) +, $#capitals, $#capitals ? 'Lots' : 'One'; 2, 1, Lots

Replies are listed 'Best First'.
Re^3: Perl Array - What an array contains
by AnomalousMonk (Archbishop) on Aug 28, 2016 at 21:40 UTC

    There's yet another pitfall associated with the use of  $#array to determine the number of elements in an array. It's possible to assign to  $[ (see perlvar) to change the base index of Perl arrays. Doing so will result in your source entry appendage(s) receiving a sharp whack, so Don't Do That!SM

    Of course, it's possible to use  $#array for this purpose in a base-agnostic way:

    c:\@Work\Perl\monks>perl -wMstrict -le "print qq{perl array base is $[}; ;; my @ra = (); print qq{A: array (@ra) is empty} if $#ra + 1 - $[ == 0; ;; @ra = (1); print qq{B: array (@ra) is empty} if $#ra + 1 - $[ == 0; " perl array base is 0 A: array () is empty c:\@Work\Perl\monks>perl -wMstrict -le "$[ = 1; print qq{perl array base is $[}; ;; my @ra = (); print qq{A: array (@ra) is empty} if $#ra + 1 - $[ == 0; ;; @ra = (1); print qq{B: array (@ra) is empty} if $#ra + 1 - $[ == 0; " Use of assignment to $[ is deprecated at -e line 1. perl array base is 1 A: array () is empty

    But an array  @array evaluated in scalar context always yields the number of array elements, so I don't understand why one would ever do this in any other way.

    BTW: It's possible to assign a number other than 0 or 1 to $[, but then you're really on thin ice, so Double-Plus-Don't Do That!


    Give a man a fish:  <%-{-{-{-<

Re^3: Perl Array - What an array contains
by hippo (Archbishop) on Aug 25, 2016 at 13:27 UTC

    Indeed, but the possibility of "no capitals" was not in the spec. :-)