GrooverMD
GrooverMD

Reputation: 147

Get the element count of this array?

I have this array and for the life of me I cannot find out how to return the element count.

I have looked through perl sites but can't seem to find the answer. How do I return the element count for the following?

my $animals = [ "dog", "cat", "canary", "mouse", ];

foreach my $i (0..$animals){ #this does not work
print $animals->[$i]
}

Upvotes: 1

Views: 1210

Answers (3)

SAHO
SAHO

Reputation: 47

My code:

my @a=qw(dog,cat,canary,mouse);
my $size=$#a+1;
print"$size\n";

Upvotes: 0

Chris Doyle
Chris Doyle

Reputation: 11992

You are creating an array reference with

my $animals = [];

So if you want to do array like actions on it then you need to dereference it. You can deference it using either of the two formats

my $count = @$animals;

or

my $count = @{$animals};

For example

perl -e '
 my $animals = [ "dog", "cat", "canary", "mouse", ]; 
 print $animals->[$_], "\n" foreach (0 .. $#$animals);
'

OUTPUT

dog
cat
canary
mouse

However this is giving you a count of the elements which you then iterate over using the index position of the array. You can do this much simpler in perl by saying

foreach my $animal (@$animals){
    print $animal, "\n";
}

Using the above example perl will iterate through the array loading each element into the variable $animal which you can then print.

Upvotes: 5

Chankey Pathak
Chankey Pathak

Reputation: 21666

How do I return the element count?

You have an arrayref. Just dereference it and use scalar to count elements in array.

my $animals = [ "dog", "cat", "canary", "mouse", ];
print scalar @$animals;

Upvotes: 1

Related Questions