The Wayback Machine - https://web.archive.org/web/20240929072321/https://www.geeksforgeeks.org/perl-arrays/
Open In App

Perl | Arrays

Last Updated : 26 Nov, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable.
arrays
 
Example:

@number = (50, 70, 46);             
@names = ("Geeks", "For", "Geeks");

Array Creation: In Perl programming every array variable is declared using “@” sign before the variable’s name. A single array can also store elements of multiple datatypes. For Example:

# Define an array
@arr = (1, 2, 3);
@arr = (1, 2, 3, "Hello");

Array creation using qw function:
qw() function is the easiest way to create an array of single-quoted words. It takes an expression as an input and extracts the words separated by a whitespace and then returns a list of those words. The best thing is that the expression can be surrounded by any delimiter like- () ” [] {} // etc. However () and // are used generally.

Syntax:

qw (Expression)
qw /Expression/
qw 'Expression'
qw {Expression}

Example :




# Perl program to demonstrate qw function
  
# using qw function
@arr1 = qw /This is a Perl Tutorial by GeeksforGeeks/;
  
# Creates array2 with elements at
# index 2,3,4 in array1
@arr2 = @arr1[2,3,4]; 
  
print "Elements of arr1 are:\n";
foreach $ele (@arr1)
{
    print "$ele \n";
}
  
print "Elements of arr2 are:\n";
foreach $ele (@arr2)
{
     print "$ele \n";
}


Output:

Elements of arr1 are:
This 
is 
a 
Perl 
Tutorial 
by 
GeeksforGeeks 
Elements of arr2 are:
a 
Perl 
Tutorial 

Accessing Array Elements: For accessing the elements of an array we must prefix “$” sign before the array variable name followed by the index in square brackets. For Example:

# Define an array
@arr = (1, 2, 3);

# Accessing and printing first 
# element of an array
print "$arr[0]\n";

# Accessing and printing second
# element of an array
print "$arr[1]\n";

Example:




# Perl program to demonstrate Array's
# creation and accessing the array's elements
  
# Creation an array fruits
@fruits = ("apple", "banana", "pineapple", "kiwi");
  
# printing the array
print "@fruits\n";
  
# Prints the array's elements
# one by one using index
print "$fruits[0]\n";
print "$fruits[1]\n";
print "$fruits[2]\n";
print "$fruits[3]\n";


Output:

apple banana pineapple kiwi
apple
banana
pineapple
kiwi

Note: Array indices always start from zero. To access the first element it must to give 0 as indices. We can also give a negative index. But giving negative index will result in selecting the array elements from ending not from the beginning.

Example:




# Perl program to demonstrate 
# negative index of array
  
# Creation an array fruits
@fruits = ("apple", "banana", "pineapple", "kiwi");
  
# Prints the array's elements
# one by one using negative index
print "$fruits[-1]\n";
print "$fruits[-2]\n";


Output:

kiwi
pineapple

Sequential Number Arrays: Perl also provides a shortcut to make a sequential array of numbers or letters. It makes out the user’s task easy. Using sequential number arrays users can skip out loops and typing each element when counting to 1000 or letters A to Z etc.

Example:

@array = (1..9); # array with numbers from 1 to 9
@array = (a..h); # array with letters from a to h

Program:




# Perl program to demonstrate
# Sequential Number Arrays
  
# Sequential Number Arrays for 
# numbers and letters
@nums = (1..9);
@letters = (a..h);
  
# Prints array- nums
print "@nums\n"; 
  
# Prints array- letters
print "@letters\n";  


Output:

1 2 3 4 5 6 7 8 9
a b c d e f g h

Size of an Array: The size of an array(physical size of the array) can be found by evaluating the array in scalar context. The returned value will be the number of elements in the array. An array can be evaluated in scalar context using two ways:

  1. Implicit Scalar Context
    $size = @array;
  2. Explicit scalar context using keyword scalar
    $size = scalar @array;

Both ways will produce the same output so it is preferred to use an implicit scalar context.

Example:




# Perl program to demonstrate 
# the length of an array
  
# declaring an array
@arr = (11, 22, 33, 44, 55, 66);
  
# Storing the length of array 
# in variable imp_size
# implicit scalar context
$imp_size = @arr;
  
# Storing the length of array
# in variable exp_size
# explicit scalar context
$exp_size = scalar @arr;
  
print "Size of arr(imp_size) $imp_size\n";
print "Size of arr(exp_size) $exp_size";


Output:

Size of arr(imp_size) 6
Size of arr(exp_size) 6

Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e.

size = maximum_index + 1

And you can find the maximum index of array by using $#array. So @array and scalar @array is always used to find the size of an array.

Example:




# Perl program to find size and 
# maximum index of an array
  
#!/usr/bin/perl
  
# Array declaration and 
# assigning values to it
@arr = (10, 17, 19, 20, 25);
  
# to find size of array
$size_of_array = @arr;
  
# to find Maximum index of array
$maximum_index = $#arr;
  
# displaying result
print "Maximum Index of the Array: $maximum_index\n";
print "The Size of the Array:  $size_of_array\n";


Output:

Maximum Index of the Array: 4
The Size of the Array:  5

Iterating through an Array: We can iterate in an array using two ways:

  • Iterating through the range: We can iterate through the range by finding the size of an array and then running a for loop from 0 to the size – 1 and then accessing the elements of the array.

    Example:




    # Perl program to illustrate 
    # iteration through range
      
    # array creation
    @arr = (11, 22, 33, 44, 55);
      
    # size of array
    $len = @arr;
      
    for ($b = 0; $b < $len; $b = $b + 1)
    {
        print "\@arr[$b] = $arr[$b]\n";
    }

    
    

    Output:

    @arr[0] = 11
    @arr[1] = 22
    @arr[2] = 33
    @arr[3] = 44
    @arr[4] = 55
    
  • Iterating through elements(foreach Loop): We can iterate through the elements using foreach loop. Using this we can directly access the elements of the array using a loop instead of running a loop over its range and then accessing the elements.

    Example:




    # Perl program to illustrate Iterating 
    # through elements(foreach Loop)
      
    # creating array
    @l = (11, 22, 33, 44, 55);
      
    # foreach loop
    foreach $a (@l)
    {
          print "$a ";
    }

    
    

    Output:

    11 22 33 44 55
    


Previous Article
Next Article

Similar Reads

Perl | Basic Syntax of a Perl Program
Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar
10 min read
Perl | Arrays (push, pop, shift, unshift)
Perl provides various inbuilt functions to add and remove the elements in an array. .string-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .string-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padding: 8px; } .string-table td:nth-child(odd) { back
3 min read
Perl | Sorting of Arrays
Perl has a built-in sort() function to sort an array of alphabets and numbers. When an array is passed to the sort() function it returns a sorted array. Syntax: sort @Array Returns: a sorted array Sorting of Arrays in Perl can be done in multiple ways: Use of ASCII values to sort an Array Use of Comparison function (cmp) Alphabetical order of Sorti
5 min read
Perl | Multidimensional Arrays
Multidimensional arrays in Perl are the arrays with more than one dimension. Technically there is no such thing as a multidimensional array in Perl but arrays are used to act as they have more than one dimension. Multi dimensional arrays are represented in the form of rows and columns, also knows as matrix. Each element of an array can be a referen
6 min read
Perl - Arrays vs Lists
Perl is a general-purpose, interpreted, dynamic programming languages. Perl has three basic data types namely, scalars, arrays and hashes. Perl Lists The list is a sequence of scalar values. However, the list is not a data structure in Perl. There are limited operations that can be performed on the list in Perl. Since no variable refers to this lis
5 min read
Perl | chomp() Function
The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &quo
2 min read
Perl | Backtracking in Regular Expression
In Perl, a Regular expression(a.k.a regexes or regexps or REs) is a way of describing a set of strings without having to list all strings in your program or simply we can say that it is a sequence of characters that are used for pattern matching. In Perl, regular expressions have different uses: Firstly, they are used in conditionals to determine w
3 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compatible Regular Expressions". To use the Regex, Bindi
6 min read
Perl | Operators | Set - 1
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their different functionality: Arithmetic OperatorsRelat
12 min read
Perl | lt operator
'lt' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise less than the string to its right. Syntax: String1 lt String2 Returns: 1 if left argument is less than the right argument Example 1: #!/usr/local/bin/perl # Initializing Strin
1 min read
Perl | chop() Function
The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters: String : It is the input string whose last characters are removed. Returns: the last removed character. Example 1: #!/usr/bin/perl # Initialising a string $string = "GfG is a computer science portal"; # Calling the chop
1 min read
Perl | rename() Function
rename() function in Perl renames the old name of a file to a new name as given by the user. Syntax: rename(old_file_path, new_file_path) Parameters: old_file_path: path of the old file along with its name new_file_path: path of the new file along with its name Returns 0 on failure and 1 on success Example: #!/usr/bin/perl -w # Calling the rename()
1 min read
Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in s
2 min read
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance
6 min read
Perl | Loops (for, foreach, while, do...while, until, Nested loops)
Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are : for Loop "for" loop
7 min read
Perl | Comparing Scalars
Prerequisite: Scalars in Perl Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. One is for numeric scalar values and one is for string scalar values. Both the types are illustrated in bel
6 min read
Perl | String functions (length, lc, uc, index, rindex)
String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows: length() lc() uc() index() rindex() length(): T
4 min read
Perl | Data Types
Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. There are 3 data types in Perl as follows: ScalarsArraysHashes(Associative Arra
3 min read
Perl | String Operators
Operators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variables and start with ($) sign in Perl. The String is
4 min read
Perl | Hashes
Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. The variable name is preceded by the dollar sign($)followed by key under curly braces and the value as
5 min read
Perl | Regular Expressions
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and
2 min read
Perl | Regex Cheat Sheet
Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. In this, set of characters together form the search pattern. It is also known as regexp. When user learns regular expression then there might be a need for quick look of those concepts which he didn't use often. So to provide
6 min read
Introduction to Perl
Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the "Pathologically Eclectic Rubbish Lister" Or "Prac
9 min read
Perl | Regex Character Classes
Character classes are used to match the string of characters. These classes let the user match any range of characters, which user don’t know in advance. Set of characters that to be matched is always written between the square bracket []. A character class will always match exactly for one character. If match not found then the whole regex matchin
3 min read
Perl | Special Character Classes in Regular Expressions
There are many different character classes implemented in Perl and some of them used so frequently that a special sequence is created for them. The aim of creating a special sequence is to make the code more readable and shorter. The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its
4 min read
Perl | Subroutines or Functions | Set - 2
Prerequisite: Subroutines or Functions in Perl A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In this article we will di
4 min read
Perl | Operators | Set - 2
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Some of the operators already discussed in Perl Operators Set - 1. Remaining operators will be d
7 min read
Perl | qw Operator
The qw operator in Perl is used to extract each element of the given string as it is in an array of elements in single-quote ( ' ' ). This function stands for quote word because it considers each word of the given string as it is quoted like qw(Geeks for Geeks) is equivalent to ('Geeks', 'for', 'Geeks'). This qw() uses parentheses so it seems like
2 min read
Perl | Reverse an array
Reverse an array or string in Perl. Iterative Way: Iterate over the array from 0 to mid of array. Swap the arr[i] element with arr[size-i] element. #Perl code to reverse an array iteratively #declaring an array of integers @arr = (2, 3, 4, 5, 6, 7); # Store length on array in $n variable $n = $#arr; #Print the original array print "The origina
2 min read
Packages in Perl
A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension .pm. Two different modules may contain a variable or a function of the same name. Any variable which is not contained in any package belongs to the main package. There
4 min read
Article Tags :