Perl Array - Create empty size array, assign zero or space with code examples

This tutorial explains multiple ways

  • create an empty-sized array with a length of zero
  • create and initialize an array with elements containing zero
  • create and initialize an array with elements containing space

How to create an empty array with zero elements in Perl

The empty array can be created in two ways

  • Declare an Array variable the variable is declared using the my keyword, followed by a variable prefixed with @.
my @numbers;

It creates a new array with an empty(zero sizes)

  • Assign with empty size

Another way to create an empty array is by assigning ()

In both cases above, It creates an empty list with a new array reference.

Here is an example

#Declare array variable
my @numbers;
print @numbers;

## Declare and assign an empty list
my @numbers1=();
print @numbers1;

Output empty array

how to create an array with initialized with zero values

the array can be assigned with elements containing zero using multiplier syntax.

syntax

(element) x n

element is an element that is populated into an array. to create an array with elements zero, use (0). x is a multiplier operator n tells the number of elements to populate

my @numbers1 = (0) x 4;
print @numbers1;
0000

How to create an array assigned with empty spaces

the array can be assigned with empty spaces using multiplier syntax.

syntax

(element) x n

element is an element that is populated into an array. to create an array with empty spaces, use ("") n tells the number of elements to populate x is a multiplier in perl

Here is an example

my @numbers1 = (" ") x 5;
print @numbers1;

How do I initialize an array in Perl?

To initialize an array, Please follow the below steps.

  • Declare an array variable using the @ prefix
  • Arrays contain any scalar values such as string, numbers, floating numbers
  • Assign an array using a list of values enclosed in ()

for example, a list of numbers is initialized in an array as given below

my @numbers=(1,2,3,4,5,6,7,8,9,10)