{

Find Array size in Perl with Code example


Perl Array length example

The array contains a list of elements unordered.

Sometimes, you need to find the number of elements i.e size. This post talks about multiple ways to know the size of an array in Perl with code examples.

Perl Array length examples

Perl allows us to use an array in a list and scalar context.

In List Content, Array returns the list of elements. Scalar Context, Array return size of an element

  • using scalar keyword

Print an array using scalar context as given below

@numbers = (11, 22, 33,44,55,66);
print scalar @numbers
  • Last Index syntax($#array)

$#arrayreturn last index of an array. If the array contains 5 elements, the $#array returns 4. So adding 1 to this returns a size of an array

@numbers = (11, 22, 33,44,55,66);
print $#numbers+1;
  • using smart match operator Perl 5.18 introduced a smart match operator (~~) in the experimental feature.

So you have to use the below line to use this feature in your code.

use experimental 'smartmatch';

printing variable with smartmatch returns a size of an array.

use warnings;
use experimental 'smartmatch';
@numbers = (11, 22, 33,44,55,66);

print 0+@numbers;
print ~~@numbers
  • using scalar context,

Create a scalar context by assigning an array to a variable. Print the array

@numbers = (11, 22, 33,44,55,66);
## Create a scalar context
my $count = @numbers;
print $count;   

How do I determine the size of an array in Perl?

To print an array size in Perl, Please follow the below steps

  • Use array variables in scalar content in multiple ways
  • first way, print using the scalar keyword of an array variable
print scalar @array
  • second, Create a scalar context by assigning an array variable to the scalar variable
@numbers = (11, 22, 33,44,55,66);
## Create a scalar context
my $count = @numbers;
print $count;   
  • It returns several elements in an array.

Which function is used to find the length of an array in Perl?

Perl allows list and scalar context, List only returns elements, and scalar returns the size of elements. So, Scalar function is used to find the length of an array in Perl

What is a scalar array in Perl?

Scalar array is a array of scalar values in perl. Scalar value contains strings, integers and floating numbers. For example, array declared as given below

@numbers = (11, 22, 33,44,55,66);
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.