Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Perl Array - What an array contains

by hippo (Bishop)
on Aug 25, 2016 at 12:47 UTC ( [id://1170423]=note: print w/replies, xml ) Need Help??


in reply to Perl Array - What an array contains

Just test $#capitals

say $#capitals ? 'Lots of capitals' : "Just one: @capitals";

Replies are listed 'Best First'.
Re^2: Perl Array - What an array contains
by pryrt (Abbot) on Aug 25, 2016 at 13:07 UTC

    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

      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:  <%-{-{-{-<

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1170423]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-19 22:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found