Home » Perl Array

Summary : in this tutorial, you’ll learn about Perl array and how to use arrays effectively in your program.

Introduction to Perl array

Perl Array

A list is immutable so you cannot change it directly. In order to change a list, you need to store it in an array  variable .

By definition, an array is a variable that provides dynamic storage for a list.

In Perl, the terms array and list are used interchangeably, but you have to note an important difference: a list is immutable whereas an array is mutable. In other words, you can modify the array’s elements, grow or shrink the array, but not a list.

A scalar variable begins with the dollar sign ( $ ), however, an array variable begins with an at-sign ( @ ).

The following example illustrates how to declare an array variable:

The $ sign looks like S in the word s calar. And @ looks like a in the word a rray, which is a simple trick to remember what type of variables you are working with.

Accessing Perl array elements

Like a list, you can access array elements using square brackets []  and indices as shown in the following example:

If you take a look at the code carefully, you will see that we used $days[0] instead of @days[0] .

This is because an array element is a scalar, you have to use the scalar prefix ( $ ). In Perl, the rule is that the prefix represents what you want to get, not what you’ve got.

Perl also allows you to access array elements using negative indices. Perl returns an element referred to by a negative index from the end of the array. For example, $days[-1] returns the last element of the array @days .

You can access multiple array elements at a time using the same technique as the list slice.

Counting Perl array elements

If you treat an array as a scalar, you will get the number of elements in the array. Take a look at the following code:

However, this code causes an error in case you don’t really want to count it but accidentally assign an array to a scalar. To be safe, use the scalar() function as follows:

The operator $#  returns the highest index of an array. See the following example:

Modifying Perl array elements

To change the value of an element, you access the element using the index and assign it a new value. Perl also allows you to change the values of multiple elements at a time.

See the following example:

Perl array operations

Perl provides several useful functions and operators to help you manipulate arrays effectively. We will cover the most important ones in the following sections.

Perl array as a stack with push() and pop() functions

Both functions treat an array as a stack. A stack works based on the last in first out (LIFO) philosophy. It works exactly the same as a stack of books. The push() function appends one or more elements to the end of the array, while the pop() function removes the last element from the end of the array.

The following example demonstrates how to use push() and pop() functions:

Perl array as a queue with unshift() and pop() functions

If the push() and pop() treat an array as a stack, the unshift() and pop() functions treat an array as a queue. A queue works based on the first in first out (FIFO) philosophy. It works like a queue of visitors. The unshift() function adds one or more elements to the front of the array, while the pop() function removes the last element of the array.

The following example demonstrates how to use the unshift() and pop() functions:

Sorting Perl arrays

Perl provides the sort() function that allows you to sort an array in alphabetical or numerical order. Here is an example of sorting an array of strings alphabetically.

The sort() function also accepts a block of code that allows you to change the sort algorithm. If you want to sort an array in numerical order, you need to change the default sorting algorithm.

Let’s take a look at the example below:

In the example above:

  • First, we had an unsorted array @a , and we displayed the @a array to make sure that it is unsorted.
  • Second, we used the sort() function to sort the @a array. We passed a block of code {$a <=>$b} and the @a array to the sort function. The $a  and $b are global variables defined by the sort() function for sorting. The operator <=> is used to compare two numbers. The code block {$a <=> $b} returns -1 if $a < $b , 0 if $a = $b , and 1 if $a > $b .
  • Third, we displayed the elements of the sorted array @a.

For more information on the sort()  function, check out the Perl sort function .

In this tutorial, we’ve introduced you to Perl array and shown you some useful techniques to manipulate array’s elements effectively.

Perl Tutorial

  • Perl Basics
  • Perl - Home
  • Perl - Introduction
  • Perl - Environment
  • Perl - Syntax Overview
  • Perl - Data Types
  • Perl - Variables
  • Perl - Scalars

Perl - Arrays

  • Perl - Hashes
  • Perl - IF...ELSE
  • Perl - Loops
  • Perl - Operators
  • Perl - Date & Time
  • Perl - Subroutines
  • Perl - References
  • Perl - Formats
  • Perl - File I/O
  • Perl - Directories
  • Perl - Error Handling
  • Perl - Special Variables
  • Perl - Coding Standard
  • Perl - Regular Expressions
  • Perl - Sending Email
  • Perl Advanced
  • Perl - Socket Programming
  • Perl - Object Oriented
  • Perl - Database Access
  • Perl - CGI Programming
  • Perl - Packages & Modules
  • Perl - Process Management
  • Perl - Embedded Documentation
  • Perl - Functions References
  • Perl Useful Resources
  • Perl - Questions and Answers
  • Perl - Quick Guide
  • Perl - Useful Resources
  • Perl - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.

Here is a simple example of using the array variables −

Here we have used the escape sign (\) before the $ sign just to print it. Other Perl will understand it as a variable and will print its value. When executed, this will produce the following result −

In Perl, List and Array terms are often used as if they're interchangeable. But the list is the data, and the array is the variable.

Array Creation

Array variables are prefixed with the @ sign and are populated using either parentheses or the qw operator. For example −

The second line uses the qw// operator, which returns a list of strings, separating the delimited string by white space. In this example, this leads to a four-element array; the first element is 'this' and last (fourth) is 'array'. This means that you can use different lines as follows −

You can also populate an array by assigning each value individually as follows −

Accessing Array Elements

When accessing individual elements from an array, you must prefix the variable with a dollar sign ($) and then append the element index within the square brackets after the name of the variable. For example −

This will produce the following result −

Array indices start from zero, so to access the first element you need to give 0 as indices. You can also give a negative index, in which case you select the element from the end, rather than the beginning, of the array. This means the following −

Sequential Number Arrays

Perl offers a shortcut for sequential numbers and letters. Rather than typing out each element when counting to 100 for example, we can do something like as follows −

Here double dot (..) is called range operator . This will produce the following result −

The size of an array can be determined using the scalar context on the array - the returned value will be the number of elements in the array −

The value returned will always be the physical size of the array, not the number of valid elements. You can demonstrate this, and the difference between scalar @array and $#array, using this fragment is as follows −

There are only four elements in the array that contains information, but the array is 51 elements long, with a highest index of 50.

Adding and Removing Elements in Array

Perl provides a number of useful functions to add and remove elements in an array. You may have a question what is a function? So far you have used print function to print various values. Similarly there are various other functions or sometime called sub-routines, which can be used for various other functionalities.

Slicing Array Elements

You can also extract a "slice" from an array - that is, you can select more than one item from an array in order to produce another array.

The specification for a slice must have a list of valid indices, either positive or negative, each separated by a comma. For speed, you can also use the .. range operator −

Replacing Array Elements

Now we are going to introduce one more function called splice() , which has the following syntax −

This function will remove the elements of @ARRAY designated by OFFSET and LENGTH, and replaces them with LIST, if specified. Finally, it returns the elements removed from the array. Following is the example −

Here, the actual replacement begins with the 6th number after that five elements are then replaced from 6 to 10 with the numbers 21, 22, 23, 24 and 25.

Transform Strings to Arrays

Let's look into one more function called split() , which has the following syntax −

This function splits a string into an array of strings, and returns it. If LIMIT is specified, splits into at most that number of fields. If PATTERN is omitted, splits on whitespace. Following is the example −

Transform Arrays to Strings

We can use the join() function to rejoin the array elements and form one long scalar string. This function has the following syntax −

This function joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns the string. Following is the example −

Sorting Arrays

The sort() function sorts each element of an array according to the ASCII Numeric standards. This function has the following syntax −

This function sorts the LIST and returns the sorted array value. If SUBROUTINE is specified then specified logic inside the SUBTROUTINE is applied while sorting the elements.

Please note that sorting is performed based on ASCII Numeric value of the words. So the best option is to first transform every element of the array into lowercase letters and then perform the sort function.

The $[ Special Variable

So far you have seen simple variable we defined in our programs and used them to store and print scalar and array values. Perl provides numerous special variables, which have their predefined meaning.

We have a special variable, which is written as $[ . This special variable is a scalar containing the first index of all arrays. Because Perl arrays have zero-based indexing, $[ will almost always be 0. But if you set $[ to 1 then all your arrays will use on-based indexing. It is recommended not to use any other indexing other than zero. However, let's take one example to show the usage of $[ variable −

Merging Arrays

Because an array is just a comma-separated sequence of values, you can combine them together as shown below −

The embedded arrays just become a part of the main array as shown below −

Selecting Elements from Lists

The list notation is identical to that for arrays. You can extract an element from an array by appending square brackets to the list and giving one or more indices −

Similarly, we can extract slices, although without the requirement for a leading @ character −

Perl array variables store an ordered list of scalar values. The array variable name begins with the @ symbol. To refer to a single element of an array, the variable name must start with a $ followed by the index of the element in square brackets ( [] ). The index of the first array element is 0.

For example:

Accessing array elements can be done with a negative index. This will select elements from the end of the array.

Perl supports a shortcut for sequential letters or numbers. Use the range operator .. to assign sequential values to array elements. For example:

The size or length of the array can be evaluated by the scalar context of the array or by using the scalar variable value of the last array element. The scalar context is refered to by scalar @array . The last array element is refered to by $#array . If @array is empty, the value of $#array is -1.

Perl offers many useful functions to manipulate arrays and their elements:

  • push(@array, element) : add element or elements into the end of the array
  • $popped = pop(@array) : delete and return the last element of the array
  • $shifted = shift(@array) : delete and return the first element of the array
  • unshift(@array) : add element or elements into the beginning of the array

Slicing an array is selecting more than one element from an array to create another array. The specification of a slice must be a list of comma-delimited valid index numbers, or using the range operator.

You can use the split() function to split a long string into separate array elements, using a value as a delimiter string.

You can use the join() function to rejoin elements of an array into a long scalar string, with an optional delimiter.

Since as an array is a comma-delimited list of values you can easily combine two arrays with the merge() function. For example:

An array holds a list of cellular phone models. A second array holds the price of each model in US Dollars. Create a third array which contains the price of each model in Pounds Sterling. Assume 1 pound equals 2 US Dollars. As the result print one line per model stating its cost in pounds.

For example: "One iPhone X costs 120 pounds."

Sphere Engine

Coding for Kids is an online interactive tutorial that teaches your kids how to code while playing!

Receive a 50% discount code by using the promo code:

Start now and play the first chapter for free, without signing up.

array assignment perl

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

last modified August 24, 2023

Perl array tutorial shows how to work with arrays in Perl.

An array is an ordered list of values. The elements of the array can be accessed by their index; the indexes start from zero.

An array is a basic Perl data type. A data type is a set of values and operations that can be done with these values.

In Perl, the terms array and list are often used interchangeably. Sometimes, programmers use the term array for the variable ( @vals ) and list for the data literal that is on the right side of the array definition, for instance: (1, 2, 3, 4, 5) .

Perl uses the @ sigil to define an array variable.

We have an array of strings.

In the tutorial, we are going to use several external modules. These can be installed with the cpanm tool.

Perl simple array

In the following example, we work with a simple array.

In the example, we work with an array of integers.

We define an array of integer values. The variable name is preceded by the @ sigil. The elements of the array are enclosed between a pair of () brackets and are separated by comma characters.

We access the elements of the array by their indexes; the first index is 0. The last element can be access with index -1. The indexes are placed between [] brackets. Since we acceass a single element, we use the $ sigil in the variable name.

We add two new values to the array.

We print the contents of the @vals array; for a cleaner output, we set the output field separator to a space.

When we use the array in a scalar context, we get the number of elements of the array. This can be also accomplised by the scalar function.

Perl access array elements

In the next example, we access array elements.

Array elements are access by their indexes. The first index has value 0. The last index is $#vals . Array elements can be accessed from the end by using negative indexes.

We print the values of four elements. The first value has index 0, the second 1. The last has index -1 and the last but one -2. The indexes are place between [] characters and the variable name is preceded with the $ sigil.

We print the number of elements with the scalar function and the last index value with $#vals .

Perl list assignment

We can assign a list of values to multiple variables in one step.

The variables are on the left side, the list literal is on the right side.

Perl command line arguments

Perl stores command line arguments in a special variable @ARGV .

In the example, we print two arguments and then the whole array with Dumper .

We end the script with usage output if there are less than three arguments. The $0 variable refers to the program name. In this expression ( if @ARGV < 3 ), the array is used in a scalar context and we compare the number of elements in the array with value 3.

Perl subroutine arguments

Perl stores arguments passed to a subroutine in a special variable @_ .

In the example, we add three values in the add3 subroutine. We utilize the @_ array to get the arguments.

Perl array is a value type

Assigning an array to another array creates its copy. In some languages such an assignment would create a reference to the original array.

We assign an array to another one and change its two values. The values of the new array are not affected.

Perl array range operator

The range .. operator allows us simplify the creation of arrays with values forming a sequence.

We use the .. operator to create an array of integers and characters.

Perl array slice

A slice is a portion of an array. Slices can be created with the .. range operator or the , comma operator.

We create a couple of slices from an array of integers.

This slice contains elements with indexes 1, 2, and -1.

This slice has elements with indexes 1 through 4.

This slice has elements starting from 5 until the last element.

Perl array contains element

In the following example, we check if the array contains the specified element.

We use the experimental ~~ "smartmatch" operator.

This line turns off the warning.

Perl qw function

Perl contains a handy qw function, which simplifies writing arrays of string values.

Using the qw function, we do not have to write the quote characters and the commas.

The Data::Dumper module is useful for debugging; we can quickly look at the contents of a data structure.

We create a list of words with qw .

Perl array push and pop

The push function appends a list of values onto the end of the array. The pop function removes and returns the last element of the array.

In the example, we append values to the array with push and remove values from the end of the array with pop .

We have an array of integers.

We append value 6 at the end of the array.

Here, we append three values at the end of the array.

With pop , we remove the last element of the array and print the removed item to the console.

Perl array shift and unshift

The unshift function appends the given list of elements at the beginning of an array, while shift removes and returns the first element of the array.

In the example, we use unshift and shift functions to add and remove values at the beginning of the array.

Perl array flattening

In Perl, arrays are flattened when combined.

When we combine @vals1 and @vals2 , we form one array containing all elements of both arrays in one level.

Perl array of arrays

To create an array of nested arrays, we place references to the arrays in the parent array. The reference to an array is created with the [] brackets.

In the example, we create a two-dimensional array of integers.

Using one index, we get the reference to a nested array. To dereference it, we use the @{} characters.

To get the element, we use two indexes in two pairs of [] brackets.

Perl array sum, min, max, product

In the next example, we compute some statistics of an array of integers.

The sum0 , min , max , and product functions are imported from the List::Util module.

The sum0 returns the numerical sum of all the elements in the @vals . It returns 0 when given an empty list.

Perl array map function

The map function applies an expression on each element of an array and returns a new array with the updated results.

We work with map function on two arrays.

Here we multiply each element in the array by 2. The $_ is a special variable, which represents the current value.

We have a list of words. We apply the lc (lowercase) function on each of the words.

Perl array classic for loop

In Perl, we can use the classic for loop, popularized by the C language, to go through the elements of an array.

We have a list of integers. Using the classic for loop, we go through the array and print all the elements.

In the for loop, we need to know the size of the array.

In the loop, we have the auxiliary variable $i , which is used as a counter. A for loop has three phases: initialization, condition and code block execution, and incrementation.

Perl array while loop

We can traverse an array with the while loop.

In this case, we also need to determine the size of the array and to use the auxiliary $i variable.

Perl array foreach loop

In a foreach loop, we run a block of code for each element of an array.

We use the foreach loop to go through the elements of an array of integers.

In each iteration, the current value is stored in the temporary $val variable.

If we omit the auxiliary variable, the current value is stored in the special $_ variable.

If the temporary variable is omitted, the for loop is a synonym for foreach .

In this example, the foreach and for loops are identical.

Perl array controlling iterations

The iterations can be controlled with next or last keywords.

The next statement is used inside a loop to start the next iteration and skip all code below it, while the last statement is used to exit the loop immediately.

In this loop, we skip all negative values. The next statement skips the say statement for values below 0, but continues with the following iteration.

In this loop, we print all positive values until the first negative value is encountered. In case we have a negative integer, we terminate the loop with the last statement.

Perl array splice

With the splice function, we can remove or replace elements of an array.

We have an array of words. We use the splice function to remove a word and replace a word.

The third element is removed. The removed element is returned. The second argument of splice is the offset, the third is the length. (We remove one element from the third position.)

We replace the third element with the word 'sunset'.

Perl array unique values

The List::MoreUtils contains helpful functions for working with arrays.

The uniq function returns a new list by stripping duplicate values. The duplicates function returns a new list containing values that have duplicates in the list.

Perl array split/join

The split function can be used to cut a string into an array of substrings. The join function can be used to form a string from a list of values.

The example uses the split and join functions.

We cut the sentence into an array of words. The sentence is cut by the space character.

With join , we can do the reverse operation. We join the words of the array into a string.

Perl array finding elements

The firstval function returns the first element in a list for which the block evaluates to true. The lastval function returns the last value in a list for which the block evaluates to true. The functions are part of the List::MoreUtils module.

In the example, we search for specific items in a list of words.

We search for the first/last string which starts with letter 'w'. We utilize a regular expression.

We search for the first/last string that has exactly three characters. We use the length function to get the size of the current word.

We search for the first/last string which contains repeated characters, such as oo or ee. Again, we use a regular expression.

Perl comparing arrays

The Array::Compare is a module for comparing arrays in Perl.

In the example, we compare array of integers and strings.

A new comparator object is created.

We pass the references to the two arrays to the compare function.

The order of the words matter; therefore, the @words1 and @words2 are not equal.

The comparator object may take optional arguments. The Case option determines if the comparing is case sensitive. If we do not provide the option, the default is case sensitive comparison.

In the example, we perform case sensitive and case insensitive comparison of two arrays of words.

Perl sort array

The sort function returns the sorted elements of the list. The original values are intact. By default, the numbers are sorted numerically and strings lexically.

In the example, we sort a list of integers and a list of strings.

Without the block structure, the numbers and strings are sorted in ascending natural order.

The block returns information how the sort should be done. The $a and $b are special global variables that hold two values from the list to sort. The spaceship operator <=> is used for comparing numbers. To compare the numbers in descending order, we swap the $a and $b variables.

The strings are compared with the cmp function.

In the next example, we show how to sort strings by their length.

We have a list of words. We sort the list lexically and then by the length of the words.

We compare the two values with the length function in the block structure. Because the length function returns the size as an integer, we use the spaceship operator.

In the next example, we sort a list of nested lists.

In the example, we sort the users by their occupation and salary.

Each nested list represents a user.

Here, we sort the users by their occupation.

Here, we sort the users by their salary.

Perl array filter

The grep function filters an array based on the given expression.

In the example, we filter a list of integer values.

This line extracts positive integers.

Here, we get all negative ones.

In this line, we get all the even numbers.

In the next example, we use a regular expression for filtering.

We define an array of words and integers. We filter out first all integers and then words.

We further use regular expressions.

First, we extract all three-letter words and then all the words with repeated characters.

The File::Find::Rule is a module for traversing directories.

In the example, we find all Perl files that are older than 180 days. The File::Find::Rule returns an array of found files.

In this article we have worked with arrays in Perl.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Perl tutorials .

Perl Onion

  •   AUTHORS
  •   CATEGORIES
  • #   TAGS

Perl arrays 101 - create, loop and manipulate

Apr 4, 2013 by David Farrell

Arrays in Perl contain an ordered list of values that can be accessed using built-in functions. They are one of the most useful data structures and frequently used in Perl programming.

Creating an array

In Perl variables are identified using sigils. Arrays use @ (as in ‘a’ for array), so the format is: @any_name_you_choose_here. Arrays are initialised by assigning a list of values (comma separated values between parentheses). Unlike more formal languages, Perl arrays can contain a mix of numbers, strings, objects and references.

Finding the array length / size

The length of an array (aka the ‘size’) is the count of the number of elements in the array. To find the array length, use the array in a scalar context:

Accessing array elements directly

Arrays can be accessed in a variety of ways: by directly accessing an element, slicing a group of elements or looping through the entire array, accessing one element at a time.

When directly accessing an array element, use the array name prefaced with the scalar sigil ($) instead of (@) and the index number of the element enclosed in square brackets. Arrays are zero-based, which means that the first element’s index number is 0 (not 1!).

The implication of zero-based indexing is that the index number of the last element in an array is equal to the length of the array minus one.

For simpler ways to access the last element of an array - see our recent article for examples.

Loop through an array with foreach

Arrays elements can be accessed sequentially using a foreach loop to iterate through the array one element at a time.

Other common functions for looping through arrays are grep and map .

shift, unshift, push and pop

Perl arrays are dynamic in length, which means that elements can be added to and removed from the array as required. Perl provides four functions for this: shift, unshift, push and pop.

shift removes and returns the first element from the array, reducing the array length by 1.

If no array is passed to shift, it will operate on @_. This makes it useful in subroutines and methods where by default @_ contains the arguments from the subroutine / method call. E.G.:

The other three array functions work similarly to shift. unshift receives and inserts a new element into the front of the array increasing the array length by 1. push receives and inserts a new element to the end of the array, increasing the array length by 1. pop removes and returns the last element in the array, reducing the array length by 1.

Check an array is null or undefined

A simple way to check if an array is null or defined is to examine it in a scalar context to obtain the number of elements in the array. If the array is empty, it will return 0, which Perl will also evaluate as boolean false. Bear in mind that this is not quite the same thing as undefined, as it is possible to have an empty array.

This article was originally posted on PerlTricks.com .

David Farrell

David is a professional programmer who regularly tweets and blogs about code and the art of programming.

Browse their articles

Something wrong with this article? Help us out by opening an issue or pull request on GitHub

To get in touch, send an email to [email protected] , or submit an issue to tpf/perldotcom on GitHub.

This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 Unported License .

Creative Commons License

Perl.com and the authors make no representations with respect to the accuracy or completeness of the contents of all work on this website and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. The information published on this website may not be suitable for every situation. All work on this website is provided with the understanding that Perl.com and the authors are not engaged in rendering professional services. Neither Perl.com nor the authors shall be liable for damages arising herefrom.

Beginner Perl Maven tutorial

  • Installing and getting started with Perl
  • The Hash-bang line, or how to make a Perl scripts executable on Linux
  • Perl Editor
  • How to get Help for Perl?
  • Perl on the command line
  • Core Perl documentation and CPAN module documentation
  • POD - Plain Old Documentation
  • Debugging Perl scripts
  • Common Warnings and Error messages in Perl
  • Prompt, read from STDIN, read from the keyboard in Perl
  • Automatic string to number conversion or casting in Perl
  • Conditional statements, using if, else, elsif in Perl
  • Boolean values in Perl
  • Numerical operators
  • String operators: concatenation (.), repetition (x)
  • undef, the initial value and the defined function of Perl
  • Strings in Perl: quoted, interpolated and escaped
  • Here documents, or how to create multi-line strings in Perl
  • Scalar variables
  • Comparing scalars in Perl
  • String functions: length, lc, uc, index, substr
  • Number Guessing game
  • Scope of variables in Perl
  • Short-circuit in boolean expressions
  • How to exit from a Perl script?
  • Standard output, standard error and command line redirection
  • Warning when something goes wrong
  • What does die do?
  • Writing to files with Perl
  • Appending to files
  • Open and read from text files
  • Don't Open Files in the old way
  • Reading and writing binary files in Perl
  • EOF - End of file in Perl
  • tell how far have we read a file
  • seek - move the position in the filehandle in Perl
  • slurp mode - reading a file in one step
  • Perl for loop explained with examples

Perl Arrays

  • Processing command line arguments - @ARGV in Perl
  • How to process command line arguments in Perl using Getopt::Long
  • Advanced usage of Getopt::Long for accepting command line arguments
  • Perl split - to cut up a string into pieces
  • How to read a CSV file using Perl?
  • The year of 19100
  • Scalar and List context in Perl, the size of an array
  • Reading from a file in scalar and list context
  • STDIN in scalar and list context
  • Sorting arrays in Perl
  • Sorting mixed strings
  • Unique values in an array in Perl
  • Manipulating Perl arrays: shift, unshift, push, pop
  • Reverse Polish Calculator in Perl using a stack
  • Using a queue in Perl
  • Reverse an array, a string or a number
  • The ternary operator in Perl
  • Loop controls: next, last, continue, break
  • min, max, sum in Perl using List::Util
  • qw - quote word
  • Subroutines and functions in Perl
  • Passing multiple parameters to a function in Perl
  • Variable number of parameters in Perl subroutines
  • Returning multiple values or a list from a subroutine in Perl
  • Understanding recursive subroutines - traversing a directory tree
  • Hashes in Perl
  • Creating a hash from an array in Perl
  • Perl hash in scalar and list context
  • exists - check if a key exists in a hash
  • delete an element from a hash
  • How to sort a hash in Perl?
  • Count the frequency of words in text using Perl
  • Introduction to Regexes in Perl 5
  • Regex character classes
  • Regex: special character classes
  • Perl 5 Regex Quantifiers
  • trim - removing leading and trailing white spaces with Perl
  • Perl 5 Regex Cheat sheet
  • What are -e, -z, -s, -M, -A, -C, -r, -w, -x, -o, -f, -d , -l in Perl?
  • Current working directory in Perl (cwd, pwd)
  • Running external programs from Perl with system
  • qx or backticks - running external command and capturing the output
  • How to remove, copy or rename a file with Perl
  • Reading the content of a directory
  • Traversing the filesystem - using a queue
  • Download and install Perl
  • Installing a Perl Module from CPAN on Windows, Linux and Mac OSX
  • How to change @INC to find Perl modules in non-standard locations
  • How to add a relative directory to @INC
  • How to replace a string in a file with Perl
  • How to read an Excel file in Perl
  • How to create an Excel file with Perl?
  • Sending HTML e-mail using Email::Stuffer
  • Perl/CGI script with Apache2
  • JSON in Perl
  • Simple Database access using Perl DBI and SQL
  • Reading from LDAP in Perl using Net::LDAP
  • Global symbol requires explicit package name
  • Variable declaration in Perl
  • Use of uninitialized value
  • Barewords in Perl
  • Name "main::x" used only once: possible typo at ...
  • Unknown warnings category
  • Can't use string (...) as an HASH ref while "strict refs" in use at ...
  • Symbolic references in Perl
  • Can't locate ... in @INC
  • Scalar found where operator expected
  • "my" variable masks earlier declaration in same scope
  • Can't call method ... on unblessed reference
  • Argument ... isn't numeric in numeric ...
  • Can't locate object method "..." via package "1" (perhaps you forgot to load "1"?)
  • Useless use of hash element in void context
  • Useless use of private variable in void context
  • readline() on closed filehandle in Perl
  • Possible precedence issue with control flow operator
  • Scalar value ... better written as ...
  • substr outside of string at ...
  • Have exceeded the maximum number of attempts (1000) to open temp file/dir
  • Use of implicit split to @_ is deprecated ...
  • Multi dimensional arrays in Perl
  • Multi dimensional hashes in Perl
  • Minimal requirement to build a sane CPAN package
  • Statement modifiers: reversed if statements
  • What is autovivification?
  • Formatted printing in Perl using printf and sprintf
  • Data::Dumper

Debugging of an array

Foreach loop and perl arrays, accessing an element of an array, indexing array, length or size of an array, loop on the indexes of an array, push on perl array, pop from perl array, shift the perl array.

Gabor Szabo

Published on 2013-03-23

Author: Gabor Szabo

array assignment perl

  • about the translations

Perl Arrays - a tutorial

Shlomi Fish

Introduction

(Editor's note: Also see our arrays howto entry for a simple introduction to the topic)

Arrays are a sequence of variables, whose members can be retrieved and assigned to by using their indices. An index passed to an array may well be, and usually is, another variable.

To refer to the $i 'th element of the array @myarray , one uses the syntax $myarray[$i] . This element can be assigned to or its value can be retrieved, with the same notation.

Array indices are whole numbers and the first index is 0. As in the length of a string, the number of elements in an array is bounded only by the amount of available memory the computer has.

The following program prints the primes up to 200:

The notation scalar(@myarray) can be used to refer to the number of elements in an array. This number is equal to the maximal index which was assigned in the array plus one. You will also see the notation $#myarray which is equal to the maximal index itself.

Thus, for example, the above program could have been written as follows:

The ',' operator

In Perl the comma ( , ) is an operator, which we often encounter in function calls. The comma concatenates two arrays. We can use it to initialize an array in one call:

We can also use it to concatenate two existing arrays:

So why it is used in function calls? In Perl every function accepts an array of arguments and returns an array of return values. That's why the comma is useful for calling functions which accept more than one argument.

Negative Indexes

The expression $myarray[-$n] is equivalent to $myarray[scalar(@myarray)-$n . I.e: subscripts with negative indexes return the $n 'th element from the end of the array. So to get the value of the last element you can write $myarray[-1] and for the second last $myarray[-2] , etc.

Note that one should also make sure that array subscripts that are continuously decremented will not underflow below 0, or else one will start getting the elements from the end of the array.

The foreach loop

By using the foreach loop we can iterate over all the elements of an array, and perform the same set of operations on each one of them. Here's an example:

The foreach loop in the example assigns each of the elements of the array which was passed to it to $i in turn, and executes the same set of commands for each value.

The for keyword and the .. operator

The for keyword in Perl means exactly the same as foreach and you can use either one arbitrarily.

In list context, the Perl range operator, .. returns a list containing a sequence of consecutive integers. In the expression $a .. $b , for example, the range operator returns the sequence of consecutive integers from $a up to and including $b

Now one can fully understand the for $i (1 .. 10) construct that we used earlier.

Built-In Array Functions - push

The push function appends an element or an entire array to the end of an array variable. The syntax is push @array_to_append_to, @array_to_append or push @array, $elem1 . For example, the primes program from earlier could be written as:

Notice that push is equivalent to typing @array = (@array, $extra_elem) , but push is recommended because it is less error-prone and it executes faster.

Built-In Array Functions - pop

pop extracts the last element from an array and returns it. Here's a short example to demonstrate it:

Built-In Array Functions - shift

shift extracts the first element of an array and returns it. The array will be changed to contain only the elements that were previously with the 1 to scalar(@array)-1 indexes.

Here's the above example, while using shift instead of pop :

Built-In Array Functions - join

The syntax is join($separator, @array) and what it does is concatenate the elements of @array while putting $separator in between. Here's an example:

which outputs:

Built-In Array Functions - reverse

The reverse function returns the array which contains the elements of the array passed to it as argument in reverse. Here's an example:

Note that by typing scalar(reverse($scalar)) you get the string that contains the characters of $scalar in reverse. scalar(reverse(@array)) concatenates the array into one string and then reverses its characters.

The x operator

The expression (@array) x $num_times returns an array that is composed of $num_times copies of @array one after the other. The expression $scalar x $num_times , on the other hand, returns a string containing $num_times copies of $scalar concatenated together string-wise.

Wrapping the left operand in parenthesis, (or not doing so), is therefore important. It is usually a good idea to assign the left part to a variable before using x so you'll have the final expression ready.

Here's an example to illustrate the use:

Can you guess what the output of this program will be?

Here's a spoiler

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Perl Programming Language
  • Introduction to Perl
  • Perl Installation and Environment Setup in Windows, Linux, and MacOS
  • Perl | Basic Syntax of a Perl Program
  • Hello World Program in Perl

Fundamentals

  • Perl | Data Types
  • Perl | Boolean Values
  • Perl | Operators | Set - 1
  • Perl | Operators | Set - 2
  • Perl | Variables
  • Perl | Modules
  • Packages in Perl

Control Flow

  • Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
  • Perl | Loops (for, foreach, while, do...while, until, Nested loops)
  • Perl | given-when Statement
  • Perl | goto statement

Arrays & Lists

Perl | arrays.

  • Perl | Array Slices
  • Perl | Arrays (push, pop, shift, unshift)
  • Perl List and its Types
  • Perl | Hash Operations
  • Perl | Multidimensional Hashes
  • Perl | Scalars
  • Perl | Comparing Scalars
  • Perl | scalar keyword
  • Perl | Quoted, Interpolated and Escaped Strings
  • Perl | String Operators
  • Perl | String functions (length, lc, uc, index, rindex)

OOP Concepts

  • Object Oriented Programming (OOPs) in Perl
  • Perl | Classes in OOP
  • Perl | Objects in OOPs
  • Perl | Methods in OOPs
  • Perl | Constructors and Destructors
  • Perl | Method Overriding in OOPs
  • Perl | Inheritance in OOPs
  • Perl | Polymorphism in OOPs
  • Perl | Encapsulation in OOPs

Regular Expressions

  • Perl | Regular Expressions
  • Perl | Operators in Regular Expression
  • Perl | Regex Character Classes
  • Perl | Quantifiers in Regular Expression

File Handling

  • Perl | File Handling Introduction
  • Perl | Opening and Reading a File
  • Perl | Writing to a File
  • Perl | Useful File-handling functions

CGI Programming

  • Perl | CGI Programming
  • Perl | File Upload in CGI
  • Perl | GET vs POST in CGI

arrays

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:

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.

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:

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.

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.

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:

  • Implicit Scalar Context $size = @array;
  • 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.

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

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.

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

Please Login to comment...

Similar reads.

  • perl-basics

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Perl Programming/Array variables

Perl syntax includes both lists and arrays.

  • 1.1 Alternate List Construction
  • 1.2 List assignments
  • 2.1 Array Assignment
  • 2.2 Arrays in scalar context
  • 2.3 Printing an Array
  • 2.4 Accessing Elements of an Array
  • 2.5 Common array functions
  • 3 Command line arguments
  • 4 Related articles

Lists [ edit | edit source ]

A list in perl is an ordered set of scalar values. It is represented in your code as a comma-separated sequence of values, which may or may not be contained in scalar variables. Lists can be used to make multiple assignments at once, and can be passed as arguments to several built-in and user-defined functions:

Alternate List Construction [ edit | edit source ]

When creating a list of several strings that do not include spaces, Perl provides a shortcut to get around typing multiple quotes and commas. Instead of

you can use the qw// operator. This operator uses any non-alpha-numeric character as a delimiter (typically the / character), and encloses a space-separated sequence of barewords. A delimiter separates the command with the arguments. The above line is identical to the following:

and both are equal to this:

The last example uses the open and close parenthesis as a different delimiter. If there is an open and close version of the delimiter you choose, you need to use them both. Otherwise just repeat the same symbol twice. For example, you cannot type qw<Paul Michael< you have to type qw<Paul Michael> .

You can also abuse the glob syntax, when the strings do not include shell metacharacters:

List assignments [ edit | edit source ]

As shown above, lists can be used to make several assignments at once. If the number of variables on the left is the same as the number of values on the right, all variables are assigned to their corresponding values, as expected.

If there are fewer variables on the left than values on the right, the 'extra' values are simply ignored:

If there are more variables on the left than values on the right, the 'extra' variables are assigned the default undef value:

The existence of list assignment creates the ability to 'swap' two variables' values without the need of an intermediary temporary variable:

Arrays [ edit | edit source ]

An array in Perl is a variable that contains a list. An array can be modified, have elements added and removed, emptied, or reassigned to an entirely different list. Just as all scalar variables start with the $ character, all array variables start with the @ character.

Array Assignment [ edit | edit source ]

Arrays are assigned lists of values. The list of values can be arbitrarily large or small (it can even contain 0 elements).

That last example exemplifies a feature of Perl known as 'array flattening'. When an array is used in a list, it is the array's elements that populate the list, not the array itself. As stated above, a list is a set of scalar values only. Therefore, the @all array contains 1000 elements, not 2.

Arrays in scalar context [ edit | edit source ]

When an array is used in scalar context - either by assigning a scalar variable to the array's value, or using it in an operation or function that expects a scalar - the array returns its size. That is, it returns the number of elements it currently contains

Printing an Array [ edit | edit source ]

There are two general ways of printing the values of an array. You can either print the list of items in the array directly, or you can interpolate the array in a double-quoted string.

In the first example, the print function is being given a list of 6 arguments: the string 'My names are: ', each of the four values in @names , and the string ".\n". Each argument is printed separated by the value of the $, variable (that defaults to the empty string), resulting in the values from the array being 'squished' together:

In the second example, the print function is being given exactly one argument: a string that contains an interpolated array. When Perl interpolates an array, the result is a string consisting of all values in the array separated by the value of the $" variable (that defaults to a single space):

Accessing Elements of an Array [ edit | edit source ]

The elements of an array are accessed using a numerical reference within square brackets. Because each item within an array is a scalar value, you need to use $ when referencing a value. The first element of an array is number 0 and all the others count up from there.

A negative number will count down from the right side of the array. This means that -1 references the last element of the array and -3 references the third to last element. Let's see some examples:

What if you need to know the last index? $#array will return it for you:

A common mistake is to do this:

In fact @array[0] is a slice (that is, a sub-array of an array) that contains one element, whereas $array[0] is a scalar that contains the value 1.

Common array functions [ edit | edit source ]

Command line arguments [ edit | edit source ].

As you may wonder, Perl scripts support command line arguments. The entire list of parameters is stored in the array @ARGV , with the first entry containing the first command line argument. If no command line parameters were passed, @ARGV is an empty array.

The array functions and operators listed above can easily be used to detect the passed command line arguments and to detect the number of arguments provided.

Related articles [ edit | edit source ]

  • Data Structures/Arrays
  • List Functions
  • Array Functions
  • Perl Arrays

array assignment perl

  • Book:Perl Programming

Navigation menu

Popular Articles

  • Perl Empty Array (Jan 05, 2024)
  • Perl Change Directory (Jan 05, 2024)
  • Perl Backticks (Jan 05, 2024)
  • Perl Vs Bash (Jan 05, 2024)
  • Perl Or Operator (Jan 05, 2024)

Switch to English

Table of Contents

Introduction to Perl Array

Understanding perl array, accessing elements in perl array, modifying perl array, adding elements to perl array, removing elements from perl array, tips and tricks.

  • In Perl, an Array is a variable that stores an ordered list of scalar values that are accessed with a numeric index. The index of the array starts from 0 and goes up to N-1, where N is the size of the array.
  • In Perl, you can access an element of an array using the index. The index is put in square brackets after the name of the array.
  • Perl allows modification of arrays. You can alter an existing element in the array by assigning a new value to it.
  • Perl provides several ways to add elements to an existing array. The push() function appends elements to the end of the array. The unshift() function adds elements to the beginning of the array.
  • Similarly, Perl provides functions to remove elements from an array. The pop() function removes the last element from the array, while the shift() function removes the first element.
  • Remember that Perl array indexes start from 0. This is a common mistake for beginners who are used to arrays in other languages where the index may start from 1.
  • Be careful when modifying arrays. If you try to access an index that does not exist, Perl will not throw an error, but it will return an undefined value.
  • Always use $ to access individual array elements. Using @ to access an individual element is a common error and will lead to unexpected results.
  • Use the scalar function to find the size of the array. This is a common task when dealing with arrays.

MarketSplash

Perl Array Manipulation: From Basics To Advanced Operations

Perl arrays are central to effective scripting and data management. This article simplifies Perl array manipulation, with concise explanations and practical examples. It's the right place to boost your Perl array skills.

Perl arrays form the backbone of efficient data management. Like a carpenter honing their chisel, every programmer should sharpen their skills in this fundamental tool. Let's explore together how to bend Perl arrays to our will, driving productivity to new heights.

array assignment perl

Understanding Perl Arrays

Creating and accessing perl arrays, array operations: adding and removing elements, sorting and filtering perl arrays, multi-dimensional arrays in perl, practical applications of perl array functions, frequently asked questions, array length and negative indices, iterating over an array.

Perl arrays are ordered collections of scalars that can hold any data type, including numbers, strings, and references to other data types. They are denoted by the @ symbol. Arrays are dynamic , meaning their size can adjust as needed when adding or removing elements.

For example:

For those who prefer visual instructions, here's an extensive video tutorial showing how to manipulate Arrays in Perl:

Accessing Array Elements

Populating arrays dynamically, extracting multiple elements.

Accessing the elements of a Perl array is done using array indices . To access a specific element, you prefix the array name with a $ symbol , followed by the element's index in square brackets.

Perl arrays are dynamic , allowing you to populate them over time as new data becomes available. To add an element at the end of an array, you can use the push function .

Perl also allows you to extract multiple elements from an array using an array slice . This is accomplished by providing a list of indices.

These operations provide the basis for creating and accessing arrays in Perl. By understanding these principles, you can start to manipulate arrays in a more complex manner.

Perl provides built-in functions to add and remove elements from arrays, enabling dynamic manipulation of array content.

Adding Elements

Removing elements, modifying elements.

The push function appends one or more elements to the end of an array.

On the flip side, the pop function removes the last element from an array and returns it.

To change an existing element in an array, you can assign a new value directly to that index .

Perl offers robust features for sorting and filtering arrays, simplifying the task of organizing and extracting data.

Sorting Arrays

Filtering arrays, custom sort and filter.

The built-in sort function arranges array elements in ascending alphabetical (ASCII) order.

Filtering arrays in Perl is typically done using the grep function, which tests each element against a certain condition.

For complex cases , you can define custom sort and filter functions using Perl subroutines .

Accessing Elements

Nested loops.

Accessing elements in a multi-dimensional array requires an additional index for each extra dimension. For example, to access 'e' in @matrix :

This code first accesses the second sub-array with $matrix[1] and then the second element of that sub-array with [1] .

Iterating over multi-dimensional arrays typically involves nested loops, one for each dimension.

This code prints each element in @matrix , separated by spaces, with each sub-array on a new line.

Modifying elements in multi-dimensional arrays works similarly to single-dimensional arrays, but with additional indices.

Multi-dimensional arrays are powerful structures that enable the storage and manipulation of complex datasets in Perl. By understanding how to create, access, and modify these structures, you can leverage Perl's full capabilities in data management.

Finding Unique Elements

Calculating average, rotating elements.

By combining the grep and first functions, you can extract the unique elements from an array.

The sum function, combined with scalar to count array elements, can compute the average of an array of numbers.

The push , pop , shift , and unshift functions can be used to rotate elements in an array.

These examples illustrate how Perl's array functions can be used to perform common data processing tasks. With a bit of creativity, these functions can be adapted to a wide variety of practical applications, simplifying your coding work and making your scripts more efficient.

Wrapping up, this exploration of Perl arrays should leave you feeling more confident in your ability to manage data with Perl. Whether it's simple array creation or complex multi-dimensional manipulation, you have the skills to tackle it.

How do I add an element to a Perl array?

You can add an element to a Perl array using the 'push' function. For instance, push @array, $element; will add $element to the end of @array.

How can I sort a Perl array?

Perl provides the 'sort' function to sort an array. By default, it sorts the elements in ASCII order. For example, my @sorted = sort @array;

How can I combine two arrays in Perl?

To combine two arrays in Perl, you can use the push function along with the array you want to add. Like so: push @array1, @array2; This will add the elements of @array2 to the end of @array1.

What is an associative array in Perl?

In Perl, associative arrays are called hashes. They are unordered collections of scalar values indexed by their associated string key.

Let’s test your knowledge!

What Does Perl Stand For?

Subscribe to our newsletter, subscribe to be notified of new content on marketsplash..

  • DESCRIPTION
  • COMMON MISTAKES
  • CAVEAT ON PRECEDENCE
  • WHY YOU SHOULD ALWAYS use VERSION
  • CODE EXAMPLES
  • Declaration of an ARRAY OF ARRAYS
  • Generation of an ARRAY OF ARRAYS
  • Access and Printing of an ARRAY OF ARRAYS
  • Declaration of a HASH OF ARRAYS
  • Generation of a HASH OF ARRAYS
  • Access and Printing of a HASH OF ARRAYS
  • Declaration of an ARRAY OF HASHES
  • Generation of an ARRAY OF HASHES
  • Access and Printing of an ARRAY OF HASHES
  • Declaration of a HASH OF HASHES
  • Generation of a HASH OF HASHES
  • Access and Printing of a HASH OF HASHES
  • Declaration of MORE ELABORATE RECORDS
  • Declaration of a HASH OF COMPLEX RECORDS
  • Generation of a HASH OF COMPLEX RECORDS
  • Database Ties

perldsc - Perl Data Structures Cookbook

# DESCRIPTION

Perl lets us have complex data structures. You can write something like this and all of a sudden, you'd have an array with three dimensions!

Alas, however simple this may appear, underneath it's a much more elaborate construct than meets the eye!

How do you print it out? Why can't you say just print @AoA ? How do you sort it? How can you pass it to a function or get one of these back from a function? Is it an object? Can you save it to disk to read back later? How do you access whole rows or columns of that matrix? Do all the values have to be numeric?

As you see, it's quite easy to become confused. While some small portion of the blame for this can be attributed to the reference-based implementation, it's really more due to a lack of existing documentation with examples designed for the beginner.

This document is meant to be a detailed but understandable treatment of the many different sorts of data structures you might want to develop. It should also serve as a cookbook of examples. That way, when you need to create one of these complex data structures, you can just pinch, pilfer, or purloin a drop-in example from here.

Let's look at each of these possible constructs in detail. There are separate sections on each of the following:

arrays of arrays

hashes of arrays

arrays of hashes

hashes of hashes

more elaborate constructs

But for now, let's look at general issues common to all these types of data structures.

# REFERENCES

The most important thing to understand about all data structures in Perl--including multidimensional arrays--is that even though they might appear otherwise, Perl @ARRAY s and %HASH es are all internally one-dimensional. They can hold only scalar values (meaning a string, number, or a reference). They cannot directly contain other arrays or hashes, but instead contain references to other arrays or hashes.

You can't use a reference to an array or hash in quite the same way that you would a real array or hash. For C or C++ programmers unused to distinguishing between arrays and pointers to the same, this can be confusing. If so, just think of it as the difference between a structure and a pointer to a structure.

You can (and should) read more about references in perlref . Briefly, references are rather like pointers that know what they point to. (Objects are also a kind of reference, but we won't be needing them right away--if ever.) This means that when you have something which looks to you like an access to a two-or-more-dimensional array and/or hash, what's really going on is that the base type is merely a one-dimensional entity that contains references to the next level. It's just that you can use it as though it were a two-dimensional one. This is actually the way almost all C multidimensional arrays work as well.

Now, because the top level contains only references, if you try to print out your array in with a simple print() function, you'll get something that doesn't look very nice, like this:

That's because Perl doesn't (ever) implicitly dereference your variables. If you want to get at the thing a reference is referring to, then you have to do this yourself using either prefix typing indicators, like ${$blah} , @{$blah} , @{$blah[$i]} , or else postfix pointer arrows, like $a->[3] , $h->{fred} , or even $ob->method()->[3] .

# COMMON MISTAKES

The two most common mistakes made in constructing something like an array of arrays is either accidentally counting the number of elements or else taking a reference to the same memory location repeatedly. Here's the case where you just get the count instead of a nested array:

That's just the simple case of assigning an array to a scalar and getting its element count. If that's what you really and truly want, then you might do well to consider being a tad more explicit about it, like this:

Here's the case of taking a reference to the same memory location again and again:

So, what's the big problem with that? It looks right, doesn't it? After all, I just told you that you need an array of references, so by golly, you've made me one!

Unfortunately, while this is true, it's still broken. All the references in @AoA refer to the very same place , and they will therefore all hold whatever was last in @array! It's similar to the problem demonstrated in the following C program:

Which will print

The problem is that both rp and dp are pointers to the same location in memory! In C, you'd have to remember to malloc() yourself some new memory. In Perl, you'll want to use the array constructor [] or the hash constructor {} instead. Here's the right way to do the preceding broken code fragments:

The square brackets make a reference to a new array with a copy of what's in @array at the time of the assignment. This is what you want.

Note that this will produce something similar:

Is it the same? Well, maybe so--and maybe not. The subtle difference is that when you assign something in square brackets, you know for sure it's always a brand new reference with a new copy of the data. Something else could be going on in this new case with the $AoA[$i]->@* dereference on the left-hand-side of the assignment. It all depends on whether $AoA[$i] had been undefined to start with, or whether it already contained a reference. If you had already populated @AoA with references, as in

Then the assignment with the indirection on the left-hand-side would use the existing reference that was already there:

Of course, this would have the "interesting" effect of clobbering @another_array. (Have you ever noticed how when a programmer says something is "interesting", that rather than meaning "intriguing", they're disturbingly more apt to mean that it's "annoying", "difficult", or both? :-)

So just remember always to use the array or hash constructors with [] or {} , and you'll be fine, although it's not always optimally efficient.

Surprisingly, the following dangerous-looking construct will actually work out fine:

That's because my() is more of a run-time statement than it is a compile-time declaration per se . This means that the my() variable is remade afresh each time through the loop. So even though it looks as though you stored the same variable reference each time, you actually did not! This is a subtle distinction that can produce more efficient code at the risk of misleading all but the most experienced of programmers. So I usually advise against teaching it to beginners. In fact, except for passing arguments to functions, I seldom like to see the gimme-a-reference operator (backslash) used much at all in code. Instead, I advise beginners that they (and most of the rest of us) should try to use the much more easily understood constructors [] and {} instead of relying upon lexical (or dynamic) scoping and hidden reference-counting to do the right thing behind the scenes.

Note also that there exists another way to write a dereference! These two lines are equivalent:

The first form, called postfix dereference is generally easier to read, because the expression can be read from left to right, and there are no enclosing braces to balance. On the other hand, it is also newer. It was added to the language in 2014, so you will often encounter the other form, circumfix dereference , in older code.

In summary:

# CAVEAT ON PRECEDENCE

Speaking of things like @{$AoA[$i]} , the following are actually the same thing:

That's because Perl's precedence rules on its five prefix dereferencers (which look like someone swearing: $ @ * % & ) make them bind more tightly than the postfix subscripting brackets or braces! This will no doubt come as a great shock to the C or C++ programmer, who is quite accustomed to using *a[i] to mean what's pointed to by the i'th element of a . That is, they first take the subscript, and only then dereference the thing at that subscript. That's fine in C, but this isn't C.

The seemingly equivalent construct in Perl, $$aref[$i] first does the deref of $aref, making it take $aref as a reference to an array, and then dereference that, and finally tell you the i'th value of the array pointed to by $AoA. If you wanted the C notion, you could write $AoA[$i]->$* to explicitly dereference the i'th item, reading left to right.

# WHY YOU SHOULD ALWAYS use VERSION

If this is starting to sound scarier than it's worth, relax. Perl has some features to help you avoid its most common pitfalls. One way to avoid getting confused is to start every program with:

This way, you'll be forced to declare all your variables with my() and also disallow accidental "symbolic dereferencing". Therefore if you'd done this:

The compiler would immediately flag that as an error at compile time , because you were accidentally accessing @aref , an undeclared variable, and it would thereby remind you to write instead:

Since Perl version 5.12, a use VERSION declaration will also enable the strict pragma. In addition, it will also enable a feature bundle, giving more useful features. Since version 5.36 it will also enable the warnings pragma. Often the best way to activate all these things at once is to start a file with:

In this way, every file will start with strict , warnings , and many useful named features all switched on, as well as several older features being switched off (such as indirect ). For more information, see "use VERSION" in perlfunc .

# DEBUGGING

You can use the debugger's x command to dump out complex data structures. For example, given the assignment to $AoA above, here's the debugger output:

# CODE EXAMPLES

Presented with little comment here are short code examples illustrating access of various types of data structures.

# ARRAYS OF ARRAYS

# declaration of an array of arrays, # generation of an array of arrays, # access and printing of an array of arrays, # hashes of arrays, # declaration of a hash of arrays, # generation of a hash of arrays, # access and printing of a hash of arrays, # arrays of hashes, # declaration of an array of hashes, # generation of an array of hashes, # access and printing of an array of hashes, # hashes of hashes, # declaration of a hash of hashes, # generation of a hash of hashes, # access and printing of a hash of hashes, # more elaborate records, # declaration of more elaborate records.

Here's a sample showing how to create and use a record whose fields are of many different sorts:

# Declaration of a HASH OF COMPLEX RECORDS

# generation of a hash of complex records, # database ties.

You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file. The first problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you also have problems with how references are to be represented on disk. One experimental module that does partially attempt to address this need is the MLDBM module. Check your nearest CPAN site as described in perlmodlib for source code to MLDBM.

perlref , perllol , perldata , perlobj

Tom Christiansen < [email protected] >

Perldoc Browser is maintained by Dan Book ( DBOOK ). Please contact him via the GitHub issue tracker or email regarding any issues with the site itself, search, or rendering of documentation.

The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the Perl issue tracker , the mailing list , or IRC to report any issues with the contents or format of the documentation.

array assignment perl

Perl Tutorial

  • Introduction to Perl
  • Installation and Environment Setup
  • Syntax of a Perl Program
  • Hello World Program in Perl
  • Perl vs C/C++
  • Perl vs Java
  • Perl vs Python

Fundamentals

  • Modes of Writing a Perl Code
  • Boolean Values
  • Variables and its Types
  • Scope of Variables
  • Modules in Perl
  • Packages in Perl
  • Number and its Types
  • Directories with CRUD operations

Input and Output

  • Use of print() and say() in Perl
  • Perl | print operator
  • Use of STDIN for Input

Control Flow

  • Decision Making
  • Perl given-when Statement
  • Perl goto operator
  • next operator
  • redo operator
  • last in loop

Arrays and Lists

  • Array Slices
  • Getting the Number of Elements of an Array
  • Reverse an array
  • Sorting of Arrays
  • Useful Array functions
  • Arrays (push, pop, shift, unshift)
  • Implementing a Stack
  • List and its Types
  • List Functions
  • Introduction to Hash
  • Working of a Hash
  • Hash Operations
  • Sorting a Hash
  • Multidimensional Hashes
  • Hash in Scalar and List Context
  • Useful Hash functions
  • Comparing Scalars
  • scalar keyword
  • Quoted, Interpolated and Escaped Strings
  • Multi-line Strings | Here Document
  • Sorting mixed Strings in Perl
  • String Operators
  • Useful String Operators
  • String functions (length, lc, uc, index, rindex)
  • Useful String functions
  • Automatic String to Number Conversion or Casting
  • Count the frequency of words in text
  • Removing leading and trailing white spaces (trim)

Object Oriented Programming in Perl

  • Introduction to OOPs
  • Constructors and Destructors
  • Method Overriding
  • Inheritance
  • Polymorphism
  • Encapsulation

Subroutines

  • Subroutines or Functions
  • Function Signature in Perl
  • Passing Complex Parameters to a Subroutine
  • Mutable and Immutable parameters
  • Multiple Subroutines
  • Use of return() Function
  • Pass By Reference
  • Recursion in Perl
  • Regular Expressions
  • Operators in Regular Expression
  • Regex Character Classes
  • Special Character Classes in Regular Expressions
  • Quantifiers in Regular Expression
  • Backtracking in Regular Expression
  • ‘e’ modifier in Regex
  • ‘ee’ Modifier in Regex
  • pos() function in Regex
  • Regex Cheat Sheet
  • Searching in a File using regex

File Handling

  • File Handling Introduction
  • Opening and Reading a File
  • Writing to a File
  • Appending to a File
  • Reading a CSV File
  • File Test Operators
  • File Locking
  • Use of Slurp Module
  • Useful File-handling functions

Context Sensitivity

  • Scalar Context Sensitivity
  • List Context Sensitivity
  • STDIN in Scalar and List Context
  • CGI Programming
  • File Upload in CGI
  • GET vs POST in CGI
  • Breakpoints of a Debugger
  • Exiting from a Script
  • Creating Excel Files
  • Reading Excel Files
  • Number Guessing Game using Perl
  • Database management using DBI
  • Accessing a Directory using File Globbing
  • Use of Hash bang or Shebang line
  • Useful Math functions

Array Slices in Perl

In Perl, "array slicing" refers to extracting a subset of elements from an array. Slices are useful when you want to access or modify multiple elements of an array at once. This tutorial will guide you through the concept of array slices in Perl.

1. What is an Array Slice?

An array slice allows you to retrieve one or more elements from an array, given their indices. You can think of it as a "sub-array" extracted from the main array.

2. Basic Syntax :

To slice an array, you provide a list of indices inside square brackets [] .

3. Using Ranges with Slices :

You can use the range operator .. to specify a range of indices:

4. Modifying Elements Using Slices :

Array slices aren't just for retrieving elements; they can also be used for modifying multiple elements simultaneously:

5. Slicing with Negative Indices :

Negative indices count from the end of the array:

6. Hash Slices :

It's not just arrays��hashes can also be sliced! For hashes, the slice retrieves the values associated with a list of keys:

7. Uses of Array Slices :

Bulk Assignment : Assign to multiple array elements at once.

Data Extraction : Extract a subset of data from a larger dataset for processing.

Parameter Passing : Sometimes functions or subroutines may want to deal with a subset of an array, and slicing makes it easy.

Best Practices:

Be Explicit : Especially when dealing with negative indices or complex slices, it's crucial to ensure that your code is readable and clear about which elements you're targeting.

Mind the Context : Remember that in scalar context, an array slice will return the last element of the slice.

Avoid Off-the-end Slices : Slicing past the end of an array won't produce an error, but it will return undef for the nonexistent elements, which may not be what you expect.

In conclusion, array slices in Perl are a powerful feature that allows you to work efficiently with multiple elements of an array (or values of a hash) simultaneously. Once you're familiar with their syntax and behavior, you'll find many uses for them in your Perl code.

Using slices to extract elements from arrays in Perl:

  • Description: Use slices to efficiently extract multiple elements from an array.
  • Code: my @numbers = (1, 2, 3, 4, 5, 6, 7, 8); # Using slices to extract elements my @subset = @numbers[1, 3, 5];

Slice notation in Perl arrays:

  • Description: Understand the syntax of slice notation in Perl arrays.
  • Code: my @colors = ('Red', 'Green', 'Blue', 'Yellow'); # Slice notation my @subset = @colors[1..2];

Getting a range of elements from a Perl array:

  • Description: Use slice notation to get a range of elements from an array.
  • Code: my @numbers = (10, 20, 30, 40, 50); # Getting a range of elements using slice notation my @range = @numbers[1..3];

Slicing and dicing arrays in Perl:

  • Description: Slice and dice arrays by extracting specific elements.
  • Code: my @letters = ('A', 'B', 'C', 'D', 'E', 'F'); # Slicing and dicing my @subset1 = @letters[1, 3, 5]; my @subset2 = @letters[0..2];

Slice assignment in Perl:

  • Description: Perform slice assignment to modify multiple elements at once.
  • Code: my @numbers = (1, 2, 3, 4, 5); # Slice assignment @numbers[1, 3] = (10, 40);

Extracting subarrays with Perl array slices:

  • Description: Use array slices to extract subarrays from multidimensional arrays.
  • Code: my @matrix = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] ); # Extracting subarrays my @row = @{$matrix[1]}; my @column = map $_->[1], @matrix;

Perl slice notation examples:

  • Description: Explore additional examples of slice notation in Perl.
  • Code: my @data = (10, 20, 30, 40, 50, 60); # Examples of slice notation my @subset1 = @data[1..3]; my @subset2 = @data[0, 2, 4];

Slice vs. splice in Perl arrays:

  • Description: Understand the difference between slice and splice operations in Perl.
  • Code: my @numbers = (1, 2, 3, 4, 5); # Using slice my @subset = @numbers[1, 3]; # Using splice for modification splice @numbers, 1, 2, 10, 20;

Advanced array slicing techniques in Perl:

  • Description: Explore advanced techniques such as conditional slicing.
  • Code: my @grades = (75, 90, 85, 60, 95); # Advanced slicing my @passing_grades = @grades[grep { $_ >= 70 } 0..$#grades];

alvin alexander

Perl array copy example: How to copy an array in Perl

Perl array copying FAQ: Can you share some examples of how to copy a Perl array?

Copying a Perl array is actually so simple it seems like a trick question, but unfortunately it's one of those things that is only easy once you know how to do it. (Personally I find the syntax a little non-standard.)

A Perl copy array example

To copy a Perl array named @array1 to a Perl array named @array2 , just use this syntax:

In other languages that seems more like @array2 is a reference to @array1, but in Perl it's a copy.

To demonstrate that this actually copies the first Perl array, here's a short Perl array copy example script to prove the point:

This simple Perl script produces the following output:

As you can see, the contents of the two Perl arrays following the copy operation are different.

As a disclaimer, I don't know how this works with more complicated objects, but I've tried this with Perl string arrays and integer arrays, and it worked as shown here with both of those.

Perl array copy example - Summary

I hope this example of how to copy a Perl array has been helpful. As usual, if you have any questions or comments, just leave a note in the Comments section below.

Help keep this website running!

  • A Perl “read file into array” example
  • Perl hash introduction tutorial
  • Perl array size/length - How to determine the size of a Perl array
  • Perl array example - search replace in a Perl array
  • Perl array push and pop syntax and examples

books by alvin

  • ZIO ZLayer: A simple “Hello, world” example (dependency injection, services)
  • A dream vacation for the meditator in your life
  • Al's Oasis
  • Window of the Poet (painting)
  • Shinzen Young on meditating in his daily life: arising, disappearing, and The Source, and love

IMAGES

  1. Beginner Perl Maven tutorial 4.5

    array assignment perl

  2. How to write to two dimensional array in perl

    array assignment perl

  3. Perl Array

    array assignment perl

  4. Perl Commands

    array assignment perl

  5. How to use variables and array in perl

    array assignment perl

  6. Perl tutorial: Lists and Arrays (Lesson 2)

    array assignment perl

VIDEO

  1. perl tutorial NO 8 Array operations add & remove

  2. Perl Programming

  3. Array Assignment

  4. Bank Array Assignment

  5. SGD Array Assignment

  6. Perl Programming Tutorial: Undefined Array Example 2024

COMMENTS

  1. Perl Array

    A list is immutable so you cannot change it directly. In order to change a list, you need to store it in an array variable.. By definition, an array is a variable that provides dynamic storage for a list. In Perl, the terms array and list are used interchangeably, but you have to note an important difference: a list is immutable whereas an array is mutable.

  2. Array initialization in Perl

    To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples: my @zeroes = (0) x 5; # (0,0,0,0,0) my @zeroes = (0) x @other_array; # A zero for each item in @other_array. # This works because in scalar context. # an array evaluates to its size.

  3. Perl

    Perl - Arrays. An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.

  4. perllol

    The simplest two-level data structure to build in Perl is an array of arrays, sometimes casually called a list of lists. It's reasonably easy to understand, and almost everything that applies here will also be applicable later on with the fancier data structures. An array of an array is just a regular old array @AoA that you can get at with two ...

  5. Arrays

    Arrays. Perl array variables store an ordered list of scalar values. The array variable name begins with the @ symbol. To refer to a single element of an array, the variable name must start with a $ followed by the index of the element in square brackets ([]). The index of the first array element is 0. For example:

  6. Perl array

    An array is an ordered list of values. The elements of the array can be accessed by their index; the indexes start from zero. An array is a basic Perl data type. A data type is a set of values and operations that can be done with these values. In Perl, the terms array and list are often used interchangeably.

  7. Perl arrays 101

    Creating an array. In Perl variables are identified using sigils. Arrays use @ (as in 'a' for array), so the format is: @any_name_you_choose_here. Arrays are initialised by assigning a list of values (comma separated values between parentheses). Unlike more formal languages, Perl arrays can contain a mix of numbers, strings, objects and ...

  8. Perl Arrays

    Variable names of arrays in Perl start with the at mark: @ . Due to our insistence on using strict you have to declare these variables using the my keyword before the first usage. Remember, all the examples below assume your file starts with. use strict; use warnings; use 5.010; Declare an array: my @names; Declare and assign values:

  9. Perl Arrays

    Perl Arrays - a tutorial. Shlomi Fish Introduction ... Array indices are whole numbers and the first index is 0. As in the length of a string, the number of elements in an array is bounded only by the amount of available memory the computer has. ... It is usually a good idea to assign the left part to a variable before using x so you'll have ...

  10. Perl

    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 Creation: In Perl programming every array variable is declared using "@" sign before the ...

  11. Perl Programming/Array variables

    An array in Perl is a variable that contains a list. An array can be modified, have elements added and removed, emptied, or reassigned to an entirely different list. ... When an array is used in scalar context - either by assigning a scalar variable to the array's value, or using it in an operation or function that expects a scalar - the array ...

  12. Understanding Perl Arrays: A Comprehensive Guide

    Introduction to Perl Array Perl is a high-level, general-purpose, interpreted, and dynamic programming language. It has been developed for a wide range of tasks including system administration, web development, network programming, GUI development, and more. ... You can alter an existing element in the array by assigning a new value to it ...

  13. perllol

    DESCRIPTION. Declaration and Access of Arrays of Arrays. The simplest thing to build an array of arrays (sometimes imprecisely called a list of lists). It's reasonably easy to understand, and almost everything that applies here will also be applicable later on with the fancier data structures. An array of an array is just a regular old array ...

  14. Perl Array Manipulation: From Basics To Advanced Operations

    Perl arrays are ordered collections of scalars that can hold any data type, including numbers, strings, and references to other data types. They are denoted by the @ symbol. Arrays are dynamic, meaning their size can adjust as needed when adding or removing elements. 💡. Creating an array in Perl is straightforward.

  15. perldsc

    The most important thing to understand about all data structures in Perl--including multidimensional arrays--is that even though they might appear otherwise, Perl @ARRAY s and %HASH es are all internally one-dimensional. They can hold only scalar values (meaning a string, number, or a reference).

  16. Array Slices in Perl

    Bulk Assignment: Assign to multiple array elements at once. Data Extraction: Extract a subset of data from a larger dataset for processing. ... Slice vs. splice in Perl arrays: Description: Understand the difference between slice and splice operations in Perl. Code:

  17. How can I create a multi-dimensional array in perl?

    The most important thing to understand about all data structures in Perl--including multidimensional arrays--is that even though they might appear otherwise, Perl @ARRAY s and %HASH es are all internally one-dimensional. They can hold only scalar values (meaning a string, number, or a reference).

  18. Perl array copy example: How to copy an array in Perl

    A Perl copy array example. To copy a Perl array named @array1 to a Perl array named @array2, just use this syntax: @array2 = @array1; In other languages that seems more like @array2 is a reference to @array1, but in Perl it's a copy. To demonstrate that this actually copies the first Perl array, here's a short Perl array copy example script to ...

  19. Adding elements to an array in Perl

    Since you have the declaration of the array within the loop, it will re-create it each time, removing any values that would have been placed in it on previous iterations of the loop. ... Unable store all the outputs to array in Perl. Related. 11913. How can I remove a specific item from an array in JavaScript? 4137. Sort array of objects by ...

  20. Find size of an array in Perl

    To find the size of an array use the scalar keyword: print scalar @array; To find out the last index of an array there is $# (Perl default variable). It gives the last index of an array. As an array starts from 0, we get the size of array by adding one to $#: print "$#array+1"; Example:

  21. Why is Perl foreach variable assignment modifying the values in the array?

    23. See perldoc perlsyn: If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

  22. How to avoid `scalar` of empty array returning `undef`?

    Use scalar( () = FLAG_NAMES ). Sounds you have use constant FLAG_NAMES => ( ); or equivalent. If so, FLAG_NAMES is equivalent to a sub that returns nothing. You are treating it as a sub that returns a reference to an empty array, but it's actually returning undef. [1] Under use strict; and use warnings;, this should be noisy and fatal.