codescracker


perl

Perl Arrays



« Previous Tutorial Next Tutorial »


Array in perl, used to store an ordered list of scalar values. Array variable in perl, are preceded by an at (@) sign. You have to use dollar ($) sign to refer to a single array's element with the variable name followed by the element's index in a square bracket [].

Create an Array in Perl

Array variables in perl, are prefixed by the at (@) sign. Here is an example, creating an array in perl.

@array = (1, 2, 3, 'hi', 'hello', 32.43, 53.32);
@names = ("Devraj", "Alok", "Deepak", "Gaurav", "Raja", "Shivam");

Access Array Elements in Perl

To access array elements in perl, just index that element inside the square bracket []. Here is an example, shows how to access array elements in perl:

#!/usr/bin/perl
		
@names = ("Deepak", "Rajat", "Ravi", "Ritesh", "Vikrant", "Hritik", "Shivam", "Ashish");

print("$names[0]\n");
print("$names[1]\n");
print("$names[2]\n");
print("$names[3]\n");
print("$names[4]\n");
print("$names[5]\n");
print("$names[6]\n");
print("$names[7]\n");

Here is the output of the above Perl program:

Deepak
Rajat
Ravi
Ritesh
Vikrant
Hritik
Shivam
Ashish

Note - Array index always starts from 0.

Perl Arrays Example

Here is an example program, illustrates array in perl:

#!/usr/bin/perl

@ages_list = (18, 19, 20);
@names_list = ("Alok", "Devraj", "Gaurav");

print("\$ages_list[0] = $ages_list[0]\n");
print("\$ages_list[1] = $ages_list[1]\n");
print("\$ages_list[2] = $ages_list[2]\n");
print("\$names_list[0] = $names_list[0]\n");
print("\$names_list[1] = $names_list[1]\n");
print("\$names_list[2] = $names_list[2]\n");

Here, we have used escape (\) sign before dollar ($) sign to make perl, not to understand it as a variable. Here is the sample output of the above perl program:

$ages_list[0] = 18
$ages_list[1] = 19
$ages_list[2] = 20
$names_list[0] = Alok
$names_list[1] = Devraj
$names_list[2] = Gaurav

Here is another program, also illustrates arrays in perl:

#!/usr/bin/perl
		
@from_1_to_10 = (1..10);
@from_a_to_z = (a..z);

print("@from_1_to_10\n");	# this will print all the numbers between 1 and 10
print("@from_a_to_z\n");	# this will print all the characters between a and z

Here is the sample output of the above perl program:

1 2 3 4 5 6 7 8 9 10
a b c d e f g h i j k l m n o p q r s t u v w x y z

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test