Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Array length with range operator

by gurpreetsingh13 (Scribe)
on Jun 06, 2013 at 06:30 UTC ( #1037374=perlquestion: print w/ replies, xml ) Need Help??
gurpreetsingh13 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I believe this must be something very simple..might be I am missing something.

For Array length, we use either $#<array-name> or scalar(<array>) or something with print to force a scalar context.

How can we create runtime arrays using range operator and get immediate length of the same.

Tried a few things and searched too, but can't find the solution.

This works-
perl -e 'my @a="aa".."zz"; print "Length=".@a;'
This also works-
perl -e 'my @a="aa".."zz"; print scalar(@a);'
This also works-
perl -e 'my @a="aa".."zz"; print @#a;'

Just if I need to do it in a single statement..

Syntax error thrown-

perl -e 'print length($("aa".."zz"));'

Syntax error thrown

perl -e 'print length(@("aa".."zz"));'

Even if I force scalar context,syntax error thrown.

perl -e 'my $len=@("aa".."zz");print $len;'

Might be I am forgetting something basic or so. Need your help please.

PS: Please don't advice on strict and warnings etc. This is just something quick and dirty.

Comment on Array length with range operator
Select or Download Code
Re: Array length with range operator
by Athanasius (Monsignor) on Jun 06, 2013 at 06:36 UTC
      Works. But I didn't want to generate a separate list variable @a.
        perl -wE "say scalar( () = 'aa' .. 'zz');"
Re: Array length with range operator
by Happy-the-monk (Monsignor) on Jun 06, 2013 at 06:39 UTC

    or try this ;-)

    perl -wE'say scalar @{["aa".."zz"]}'

    Cheers, Sören

    (hooked on the Perl Programming language)

      Thanks.

      Good trick.

      Anonymous array - then convert the ref. back to array and apply scalar to it.

        Also works for "highest index" rather than "number of elements":

        >perl -wMstrict -lE "say scalar $#{[ 'aa' .. 'zz' ]}; " 675
Re: Array length with range operator
by kcott (Abbot) on Jun 06, 2013 at 06:42 UTC
Re: Array length with range operator
by hbm (Hermit) on Jun 07, 2013 at 19:05 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1037374]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (11)
As of 2014-07-30 14:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (234 votes), past polls