http://qs1969.pair.com?node_id=448808

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

I'm sure that this has been asked before, but can't find anything on here. If one has an array .. is there a way of finding out how many elements are in it?

Replies are listed 'Best First'.
Re: how many elements in array?
by tlm (Prior) on Apr 18, 2005 at 12:30 UTC
```my \$how_many = @array;

the lowliest monk

Re: how many elements in array?
by moot (Chaplain) on Apr 18, 2005 at 15:00 UTC
All of the previous responses are correct in that they will tell you the size of an array (which is not quite what you asked for), however you may also be thinking that an element is any defined value, which does not necessarily give the same answer - a large array might be quite sparse (although an application of this escapes me right now).

```my @a = (1, undef, 3);

# Now scalar @a = 3, but there are only two elements of interest.
# Brute force counting method:

my \$c = 0;
\$c++ for (grep { defined } @a);

# \$c now holds the number of defined elements, in this case 2.

Or simply

```my \$c = grep defined, @a;

the lowliest monk

Ah, yes, or that :/
Re: how many elements in array?
by Anonymous Monk on Apr 18, 2005 at 13:20 UTC
```my \$c1  = 0;
\$c1 += 1 for @array;

my \$c2  = grep {\$_ || !\$_} @array;

my \$c3 = 0;
L1: goto L2 unless @array % 2;
\$c3++;
pop @array;
L2: goto L3 unless @array;
\$c3 *= 2;
splice @array, 0 @array / 2;
goto L1;
L3:

my \$c4 = do {local \$" = "+"; eval "@{[map {1} @array]}"};

my \$c5 = length join "", map " ", @array;

use POSIX 'ceil';
my \$c6 = ceil((length join " ", map "", @array)/2);

my \$c7 = 0;
\$c7++, shift @array while @array;
Re: how many elements in array?
by tcf03 (Deacon) on Apr 18, 2005 at 12:34 UTC
or
```#!/usr/bin/perl -w
use strict;

my @one=(1,2,3,4,5,6);
print scalar(@one);
or
```print \$#one;
depends on what you want.
UPDATE
you should also check out the the basic datatypes, three node
tcf03,
\$#one and scalar @one do not produce the same thing. Using scalar @one gives the number of elements, which is what was asked for, while \$#one gives is the index of the last element.

Cheers - L~R

Although, technically, they actually could produce the same thing, if one were to modify \$[ to be 1

Update: Just a caveat that this is not recommended in the slightest :) as the docs for index say:
The return value is based at 0 (or whatever you've set the \$[ variable to--but don't do that).
--------------
"But what of all those sweet words you spoke in private?"
"Oh that's just what we call pillow talk, baby, that's all."

Helpful in a loop as in:

```for ( 0 .. \$#one ) {
...do stuff to each element...
}