Perl | Useful Array functions

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.
Array in Perl provides various inbuilt functions to perform operations like adding and removing elements from a pre-defined array.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl 
    
# Initalizing the array 
@x = ('Java', 'C', 'C++'); 
    
# Print the Inital array 
print "Original array: @x \n"
  
# Using push() function 
# Pushing multiple values in the array 
push(@x, 'Python', 'Perl'); 
print("Pushing new values...\n");
    
# Printing the array 
print "Updated array: @x\n"
  
# Using pop() function
print("\nPopping the last element...\n");
  
# Prints the value returned by pop 
print "Value returned by pop: ", pop(@x); 
    
# Prints the array after pop operation 
print "\nUpdated array: @x"

chevron_right


Output:



Original array: Java C C++ 
Pushing new values...
Updated array: Java C C++ Python Perl

Popping the last element...
Value returned by pop: Perl
Updated array: Java C C++ Python

 

Some useful array functions are listed below:

Function Description
push() Used to push a list of values onto the end of the array
pop() Returns the last element of Array passed to it as an argument, removing that value from the array
shift() Returns the first value in an array, removing it and shifting the elements of the array list to the left by one
unshift() Places the given list of elements at the beginning of an array, shifting all the values to the right
sort() Used to sort a list with or without the use of method of sorting
wantarray() Returns True if the currently executing subroutine expects to return a list value, and false if it is looking for a scalar value.
exists() Used to check whether an element in an given array or hash exists or not
grep() Used to extract any element from the given array which evaluates the true value for the given regular expression
join() Combines the elements of LIST into a single string using the value of VAR to separate each element


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.