jflevi has asked for the wisdom of the Perl Monks concerning the following question:

Hi Good Monks, I want to print the number of elements in an array.
print @my_array; # no good: "print" works in a list context print ($#my_array + 1); # OK only if "$[" set to 0 print (0 + @my_array); # works, but looks ugly
There must be some better way to force @my_array as a scalar or do I have flashbacks of "C" ???

I must be missing something ... actually I'm missing a lot of things :-)

Life is tough, it's tougher when you are dumb...

jfl

Replies are listed 'Best First'.
Re: Printing the length of an array ?
by kyle (Abbot) on Mar 30, 2008 at 20:50 UTC

    print scalar @my_array; (see scalar).

      Thanks kyle !

      Exactly what I wanted, short and sweet..

      Totally forgot about the "scalar" operator (if I ever knew about it)

      Life is tough, it's tougher when you are dumb...

      jfl

Re: Printing the length of an array ?
by FunkyMonk (Bishop) on Mar 30, 2008 at 21:00 UTC
    There's ways other than kyle's very reasonable suggestion of scalar. You just have to force scalar context. Here's a couple of different ways that spring to mind:
    print 0+@my_array; print "length = " . @my_array;

Re: Printing the length of an array ?
by jwkrahn (Abbot) on Mar 30, 2008 at 22:20 UTC
    updated ... twice
    $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print ~~@array' 7 $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print -(-@array)' 7 $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print 0+@array' 7 $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print 1*@array' 7 $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print @array/1' 7 $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print @array-0' 7 $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print @array x1' 7 $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print @array%~0' 7 $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print @array**1' 7
      $ perl -le'my @array = qw/1 2 3 4 5 6 7/; print -+- @array' 7
Re: Printing the length of an array ?
by ww (Archbishop) on Mar 30, 2008 at 21:14 UTC
    or, perhaps canonically, but definitely NOT canonically (see FunkyMonk's below),
    #! /usr/bin/perl use strict; use warnings; my @array = qw/1 2 3 4 5 6 7/; print "number of elements is " . ++$#array . "\n";

    The increment is necessary because the first element is @array[0].

    This produces:

    ww@GIG:~/pl_test$ perl elementsinarray.pl number of elements is 7
      The ++ makes the array one element longer, adding an undef at the end:
      my @array = qw/1 2 3 4 5 6 7/; print "number of elements is " . ++$#array . "\n"; print Dumper \@array;

      number of elements is 7 $VAR1 = [ '1', '2', '3', '4', '5', '6', '7', undef ];

        Correct!

        Better, and clearer, to write for line 7:

        my $count = $#array; print "number of elements is " . ++$count . "\n";
Re: Printing the length of an array ?
by Jenda (Abbot) on Mar 31, 2008 at 17:51 UTC