Dave's Brain

Browse - programming tips - perl get array size

Date: 2008may21
Language: perl

Q.  What's the nicest way to get the size of a perl array?

A.  Tutorials usually use the # operator.
If @a is an array $#a will give one less than the size of
the array.  The upper index.

But I prefer using scalar(@a) which da-da give the exact size
of the array.  Much nicer.

For example:

@a = qw(one two three);

$n = $#a + 1;
print "There are $n elements in the array\n";

$n = scalar(@a);
print "There are $n elements in the array\n";

# In a loop $# is fine...

for ($i = 0; $i <= $#a; $i++)
{
        print "$a[$i]\n";
}

# But checking if an array is empty, scalar is clearer...

if (scalar(@a) > 0)
{
	# Non-empty
}

if ($#a >= 0)
{
	# Non-empty
}

# Checking that an array has the required 5 elements, scalar is much
# clearer...

if (scalar(@a) == 5)
{
	# got em
}

if ($#a == 4)
{
	# Yes, got all 5 - huh?
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: