Perl Arrays
A Perl array is a list variable that stores scalar values, and the variables can be of different types.
Array variables start with the @
symbol. To access array elements, use the format $ + variable name + [index value], as shown in the example below:
Example
#!/usr/bin/perl
@hits = (25, 30, 40);
@names = ("google", "tutorialpro", "taobao");
print "\$hits[0] = $hits[0]\n";
print "\$hits[1] = $hits[1]\n";
print "\$hits[2] = $hits[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";
In the program, the $
symbol is escaped with \
to output it as is.
Executing the above program will produce the following output:
$hits[0] = 25
$hits[1] = 30
$hits[2] = 40
$names[0] = google
$names[1] = tutorialpro
$names[2] = taobao
Creating Arrays
Array variables start with the @ symbol, and elements are placed inside parentheses. You can also start the definition with qw.
@array = (1, 2, 'Hello');
@array = qw/This is an array/;
The second array uses the qw// operator, which returns a list of strings separated by spaces. You can also define arrays over multiple lines:
@days = qw/google
taobao
...
tutorialpro/;
You can also assign values to arrays by index, as shown below:
$array[0] = 'Monday';
...
$array[6] = 'Sunday';
Accessing Array Elements
To access array elements, use the format $ + variable name + [index value], as shown in the example below:
Example
@sites = qw/google taobao tutorialpro/;
print "$sites[0]\n";
print "$sites[1]\n";
print "$sites[2]\n";
print "$sites[-1]\n"; # Negative index, reverse access
Executing the above program will produce the following output:
google
taobao
tutorialpro
tutorialpro
Array indices start from 0, meaning 0 is the first element, 1 is the second element, and so on.
Negative indices access elements from the end, with -1 being the last element, -2 the second last, and so on.
Array Sequences
Perl provides an array format that can output sequences, using the format start value + .. + end value, as shown in the example below:
Example
#!/usr/bin/perl
@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = ('a'..'z');
print "@var_10\n"; # Outputs 1 to 10
print "@var_20\n"; # Outputs 10 to 20
print "@var_abc\n"; # Outputs a to z
Executing the above program will produce the following output:
1 2 3 4 5 6 7 8 9 10
10 11 12 13 14 15 16 17 18 19 20
a b c d e f g h i j k l m n o p q r s t u v w x y z
Array Size
The size of an array is determined by the scalar context of the array:
Example
@array = (1,2,3);
print "Array size: ", scalar @array, "\n";
Executing the above program will produce the following output:
Array size: 3
The array length returns the physical size of the array, not the number of elements. Consider the following example:
Example
#!/usr/bin/perl
@array = (1,2,3);
$array[50] = 4;
$size = @array;
$max_index = $#array;
print "Array size: $size\n";
print "Maximum index: $max_index\n";
Executing the above program will produce the following output:
Array size: 51
Maximum index: 50
From the output, it is clear that there are only four elements in the array, but the array size is 51.
Adding and Removing Array Elements
Perl provides useful functions to add and remove elements from arrays.
If you are new to programming, you might wonder what a function is. The print function we used earlier is an example.
The table below lists common array manipulation functions:
| No. | Type and Description | | --- | --- |
- push @ARRAY, LIST - Appends the values of the list to the end of the array.
- pop @ARRAY - Removes the last value of the array.
- shift @ARRAY - Removes the first value of the array and returns it. The index values of the array are also decremented by one.
- unshift @ARRAY, LIST - Inserts the list at the beginning of the array and returns the number of elements in the new array.
Example
#!/usr/bin/perl
# Create a simple array
@sites = ("google", "tutorialpro", "taobao");
$new_size = @sites;
print "1. \@sites = @sites\n"."Original array length: $new_size\n";
# Add an element to the end of the array
$new_size = push(@sites, "baidu");
print "2. \@sites = @sites\n"."New array length: $new_size\n";
# Add an element to the beginning of the array
$new_size = unshift(@sites, "weibo");
print "3. \@sites = @sites\n"."New array length: $new_size\n";
# Remove the last element of the array
$new_byte = pop(@sites);
print "4. \@sites = @sites\n"."Popped element: $new_byte\n";
# Remove the first element of the array
$new_byte = shift(@sites);
print "5. \@sites = @sites\n"."Popped element: $new_byte\n";
Executing the above program will output:
Slicing Arrays
We can slice an array and return the new array:
Example
#!/usr/bin/perl
@sites = qw/google taobao tutorialpro weibo qq facebook 网易/;
@sites2 = @sites[3,4,5];
print "@sites2\n";
Executing the above program will output:
weibo qq facebook
Array indices need to specify valid index values, which can be positive or negative, and each index value is separated by a comma.
If the indices are consecutive, you can use .. to denote a range:
Example
#!/usr/bin/perl
@sites = qw/google taobao tutorialpro weibo qq facebook 网易/;
@sites2 = @sites[3..5];
print "@sites2\n";
Executing the above program will output:
weibo qq facebook
Replacing Array Elements
In Perl, array elements are replaced using the splice() function, with the following syntax:
splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ]
Parameters:
- @ARRAY: The array to be replaced.
- OFFSET: The starting position.
- LENGTH: The number of elements to replace.
- LIST: The list of replacement elements.
The following example replaces 5 elements starting from the 6th element:
Example
#!/usr/bin/perl
@nums = (1..20);
print "Before replacement - @nums\n";
splice(@nums, 5, 5, 21..25);
print "After replacement - @nums\n";
Executing the above program will output:
Before replacement - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After replacement - 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20
Converting Strings to Arrays
In Perl, strings are converted to arrays using the split() function, with the following syntax:
split [ PATTERN [ , EXPR [ , LIMIT ] ] ]
Parameters:
- PATTERN: The delimiter, default is a space.
- EXPR: Specifies the number of strings.
- LIMIT: If specified, returns the number of elements in the array.
Example
#!/usr/bin/perl
# Define strings
$var_test = "tutorialpro";
$var_string = "www-tutorialpro.org";
$var_names = "google,taobao,tutorialpro,weibo";
# Convert strings to arrays
@test = split('', $var_test);
@string = split('-', $var_string);
@names = split(',', $var_names);
o
com
weibo
Convert Array to String
In Perl, to convert an array to a string, use the join()
function. The syntax is as follows:
join EXPR, LIST
Parameters:
EXPR: The delimiter.
LIST: The list or array.
Example
#!/usr/bin/perl
# Define strings
$var_string = "www-tutorialpro.org";
$var_names = "google,taobao,tutorialpro,weibo";
# Convert strings to arrays
@string = split('-', $var_string);
@names = split(',', $var_names);
# Convert arrays to strings
$string1 = join( '-', @string );
$string2 = join( ',', @names );
print "$string1\n";
print "$string2\n";
Output:
www-tutorialpro.org
google,taobao,tutorialpro,weibo
Sorting Arrays
In Perl, array sorting is done using the sort()
function. The syntax is as follows:
sort [ SUBROUTINE ] LIST
Parameters:
SUBROUTINE: Specifies the sorting rule.
LIST: The list or array.
Example
#!/usr/bin/perl
# Define array
@sites = qw(google taobao tutorialpro facebook);
print "Before sorting: @sites\n";
# Sort the array
@sites = sort(@sites);
print "After sorting: @sites\n";
Output:
Before sorting: google taobao tutorialpro facebook
After sorting: facebook google tutorialpro taobao
Note: Array sorting is based on ASCII numeric values. It's advisable to convert elements to lowercase before sorting.
Special Variable: $[
The special variable $[ represents the first index of an array, typically 0. Setting $[ to 1 changes the first index to 1, the second to 2, and so on. Here's an example:
Example
#!/usr/bin/perl
# Define array
@sites = qw(google taobao tutorialpro facebook);
print "Sites: @sites\n";
# Set the first index of the array to 1
$[ = 1;
print "\@sites[1]: $sites[1]\n";
print "\@sites[2]: $sites[2]\n";
Output:
Sites: google taobao tutorialpro facebook
@sites[1]: google
@sites[2]: taobao
It's generally not recommended to use the special variable $[ as it's deprecated in newer Perl versions.
Merging Arrays
Arrays can be merged using commas, as elements in an array are separated by commas. Here's how:
Example
#!/usr/bin/perl
@numbers = (1,3,(4,5,6));
print "numbers = @numbers\n";
Output:
numbers = 1 3 4 5 6
Multiple arrays can also be embedded into a main array and merged:
Example
#!/usr/bin/perl
@odd = (1,3,5);
@even = (2, 4, 6);
@numbers = (@odd, @even);
print "numbers = @numbers\n";
Output:
numbers = 1 3 5 2 4 6
Selecting Elements from a List
A list can be treated as an array, and specific elements can be accessed by specifying the index:
Example
#!/usr/bin/perl
$var = (5,4,3,2,1)[4];
print "Value of var = $var\n";
Output:
Value of var = 1
Ranges can also be used to select elements within an array:
Example
#!/usr/bin/perl
@numbers = (1..10)[1,3,5,7];
print "Selected numbers = @numbers\n";
Output:
Selected numbers = 2 4 6 8
@list = (5,4,3,2,1)[1..3];
print "list's value = @list\n";
Executing the above program, the output is:
list's value = 4 3 2