Perl Arrays
Perl - Arrays
Section titled “Perl - Arrays”An array in Perl is an ordered list of scalar values. Array variable names are prefixed with an “at” sign (@). To access a single element of an array, you use a dollar sign ($) with the array name, followed by the element’s index in square brackets (e.g., $array[0]).
It’s standard practice to use use strict; and use warnings; at the beginning of your Perl scripts for better error checking and code quality.
Example of array declaration and access:
#!/usr/bin/perluse strict;use warnings;
my @ages = (25, 30, 40);my @names = ("John Paul", "Lisa", "Kumar");
print "Ages[0]: $ages[0]\n"; # Output: Ages[0]: 25print "Ages[1]: $ages[1]\n"; # Output: Ages[1]: 30print "Names[1]: $names[1]\n"; # Output: Names[1]: Lisa
# Print all elements of an arrayprint "All names: @names\n"; # Output: All names: John Paul Lisa KumarIn Perl, “list” refers to the ordered collection of data itself, while “array” is a variable that holds such a list.
Array Creation
Section titled “Array Creation”Arrays are typically created using parentheses () or the qw// (quote word) operator for lists of simple strings.
my @numbers = (1, 2, 3, 4, 5);my @strings = ('apple', 'banana', 'cherry');
# Using qw// for lists of words (automatically quotes them and splits by whitespace)my @weekdays = qw(Mon Tue Wed Thu Fri Sat Sun);# Equivalent to: my @weekdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
# qw can use other delimiters too:my @colors = qw!red green blue!;my @symbols = qw#alpha beta gamma#;You can also create an empty array: my @empty_array = ();
Accessing Array Elements
Section titled “Accessing Array Elements”Array indices start at 0. You can also use negative indices to access elements from the end of the array (-1 is the last element, -2 is the second to last, etc.).
#!/usr/bin/perluse strict;use warnings;
my @days = qw(Mon Tue Wed Thu Fri Sat Sun);
print "First day: $days[0]\n"; # Output: First day: Monprint "Third day: $days[2]\n"; # Output: Third day: Wedprint "Last day: $days[-1]\n"; # Output: Last day: Sunprint "Second to last: $days[-2]\n"; # Output: Second to last: SatSequential Number/Letter Arrays (Ranges)
Section titled “Sequential Number/Letter Arrays (Ranges)”Perl’s range operator .. can be used to create arrays of sequential numbers or letters.
#!/usr/bin/perluse strict;use warnings;
my @first_ten = (1..10); # (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)my @some_letters = ('a'..'f'); # ('a', 'b', 'c', 'd', 'e', 'f')
print "Numbers: @first_ten\n";print "Letters: @some_letters\n";Array Size
Section titled “Array Size”To get the number of elements in an array, evaluate the array in scalar context.
my @my_array = (10, 20, 30);my $size = @my_array; # $size is 3
print "Array size: ", scalar(@my_array), "\n"; # Another way to force scalar contextprint "Array size: $#my_array + 1\n"; # $#array gives the last index$#array_name gives the index of the last element in @array_name. So, the size is $#array_name + 1. If the array is empty, $#array_name is -1.
Adding and Removing Elements
Section titled “Adding and Removing Elements”Perl provides functions to add/remove elements from the beginning or end of an array:
| Function | Description |
|---|---|
push @ARRAY, LIST | Appends elements of LIST to the end of @ARRAY. Returns the new number of elements. |
pop @ARRAY | Removes and returns the last element of @ARRAY. |
unshift @ARRAY, LIST | Prepends elements of LIST to the beginning of @ARRAY. Returns the new number of elements. |
shift @ARRAY | Removes and returns the first element of @ARRAY. |
#!/usr/bin/perluse strict;use warnings;
my @fruits = qw(apple banana);print "Initial: @fruits\n";
push @fruits, 'orange', 'grape';print "After push: @fruits\n"; # apple banana orange grape
my $last_fruit = pop @fruits;print "Popped: $last_fruit, Array: @fruits\n"; # grape, Array: apple banana orange
unshift @fruits, 'mango';print "After unshift: @fruits\n"; # mango apple banana orange
my $first_fruit = shift @fruits;print "Shifted: $first_fruit, Array: @fruits\n"; # mango, Array: apple banana orangeSlicing Array Elements
Section titled “Slicing Array Elements”An array slice allows you to select multiple elements from an array by their indices, forming a new list (which can be assigned to another array).
#!/usr/bin/perluse strict;use warnings;
my @days = qw(Mon Tue Wed Thu Fri Sat Sun);
# Get specific elementsmy @work_days = @days[0, 1, 2, 3, 4]; # Mon Tue Wed Thu Friprint "Work days: @work_days\n";
# Get a range of elementsmy @mid_week = @days[1..3]; # Tue Wed Thu (indices 1, 2, 3)print "Mid week: @mid_week\n";
# Slices can use any valid indices, including negative onesmy @ends = @days[0, -1]; # Mon Sunprint "Ends: @ends\n";Modifying Array Elements with splice
Section titled “Modifying Array Elements with splice”The splice function is powerful for modifying arrays: it can remove elements, add new elements, or do both at a specific position.
splice @ARRAY, OFFSET, [LENGTH, [LIST]]@ARRAY: The array to modify.OFFSET: Starting index for modification. Negative offset counts from the end.LENGTH(optional): Number of elements to remove starting fromOFFSET.LIST(optional): Elements to insert into the array atOFFSETafter removingLENGTHelements.
splice returns a list of the elements removed from @ARRAY.
#!/usr/bin/perluse strict;use warnings;
my @letters = ('a'..'g'); # a b c d e f gprint "Original: @letters\n";
# Remove 2 elements starting at index 2 ('c', 'd')my @removed = splice @letters, 2, 2;print "Removed: @removed, Array: @letters\n"; # Removed: c d, Array: a b e f g
# Reset for next example@letters = ('a'..'g');
# Remove 1 element at index 1 ('b') and insert 'X', 'Y'@removed = splice @letters, 1, 1, 'X', 'Y';print "Removed: @removed, Array: @letters\n"; # Removed: b, Array: a X Y c d e f g
# Reset for next example@letters = ('a'..'g');# Insert 'Z' at index 3 without removing anythingsplice @letters, 3, 0, 'Z';print "Array after insert: @letters\n"; # a b c Z d e f gConverting Strings to Arrays (split)
Section titled “Converting Strings to Arrays (split)”The split function breaks a string into a list of substrings based on a delimiter pattern.
split /PATTERN/, EXPR, [LIMIT]#!/usr/bin/perluse strict;use warnings;
my $csv_data = "apple,banana,cherry,date";my @fruits = split /,/, $csv_data;print "Fruits: @fruits\n"; # Fruits: apple banana cherry date
my $sentence = "This is a sample sentence.";# Split by whitespace (default if PATTERN omitted or is ' ')my @words = split /\s+/, $sentence; # Using explicit whitespace pattern# my @words = split ' ', $sentence; # Common idiom for splitting on whitespaceprint "Words: @words\n"; # Words: This is a sample sentence.
# Limit the number of splitsmy $path = "/usr/local/bin/perl";my @parts = split /\//, $path, 3; # Limit to 3 parts (2 splits)print "Path parts: @parts\n"; # Path parts: usr local/bin/perl (first part is empty due to leading /)Converting Arrays to Strings (join)
Section titled “Converting Arrays to Strings (join)”The join function combines the elements of a list into a single string, using a specified separator string.
join SEPARATOR, LIST#!/usr/bin/perluse strict;use warnings;
my @items = qw(one two three four);my $joined_string = join '-', @items;print "Joined with '-': $joined_string\n"; # Joined with '-': one-two-three-four
my $no_sep_string = join '', @items;print "Joined with empty: $no_sep_string\n"; # Joined with empty: onetwothreefourSorting Arrays (sort)
Section titled “Sorting Arrays (sort)”The sort function sorts a list and returns the sorted list. By default, it sorts alphabetically (ASCIIbetical order).
sort [SUBROUTINE_OR_BLOCK] LIST#!/usr/bin/perluse strict;use warnings;
my @names = qw(Alice Charlie Bob David);my @sorted_names = sort @names;print "Sorted names (alpha): @sorted_names\n"; # Alice Bob Charlie David
my @numbers = (10, 2, 100, 5, 25);my @alpha_sorted_numbers = sort @numbers;print "Sorted numbers (alpha): @alpha_sorted_numbers\n"; # 10 100 2 25 5 (wrong for numeric)
# Numeric sort using a comparison blockmy @numerically_sorted_numbers = sort { $a <=> $b } @numbers;print "Sorted numbers (numeric): @numerically_sorted_numbers\n"; # 2 5 10 25 100
# Reverse numeric sortmy @reverse_numeric = sort { $b <=> $a } @numbers;print "Sorted numbers (reverse numeric): @reverse_numeric\n"; # 100 25 10 5 2Inside the sort block, $a and $b are special package variables holding two elements being compared. The block should return -1 if $a comes before $b, 0 if they are equal, or 1 if $a comes after $b. The spaceship operator <=> does this for numbers, and cmp does it for strings.
The $[ Special Variable (Deprecated and Removed)
Section titled “The $[ Special Variable (Deprecated and Removed)”Older versions of Perl had a special variable $[ that could change the starting index of arrays (default 0). This variable is heavily deprecated and its use has always been strongly discouraged. It was removed entirely in Perl 5.30 (released in 2019). Do not use $[ in modern Perl code. All arrays in Perl are 0-indexed.
Merging Arrays
Section titled “Merging Arrays”You can merge arrays by simply including them in a list assigned to a new array.
#!/usr/bin/perluse strict;use warnings;
my @odd = (1, 3, 5);my @even = (2, 4, 6);
my @numbers = (@odd, @even, 7, 8);print "Merged numbers: @numbers\n"; # 1 3 5 2 4 6 7 8
# You can also embed list literals directlymy @mixed = (10, 20, (30, 40), 50);print "Mixed: @mixed\n"; # 10 20 30 40 50Selecting Elements from Literal Lists
Section titled “Selecting Elements from Literal Lists”You can apply array indexing and slicing directly to a list literal (a list in parentheses).
#!/usr/bin/perluse strict;use warnings;
my $third_element = (10, 20, 30, 40, 50)[2];print "Third element from list: $third_element\n"; # 30
my @slice_from_list = (qw(a b c d e f))[1..3];print "Slice from list: @slice_from_list\n"; # b c d