Notifications
Clear all
Topic starter 01/08/2025 11:35 pm
Perl arrays are a fundamental and flexible feature of the language—great for storing ordered lists of scalars (like strings or numbers). Here’s a breakdown to get you rolling:
📦 What Is an Array in Perl?
- A Perl array is a variable that holds an ordered list of scalar values
- Arrays are prefixed with
@when referenced, but individual elements use$because they’re scalars
my @colors = ('red', 'green', 'blue');
🛠 Accessing Array Elements
- Use zero-based indexing: the first element is at index
0
print $colors[0]; # prints 'red'
print $colors[2]; # prints 'blue'
🎭 Modifying Arrays
- Add elements:
push @array, $value;— adds to the endunshift @array, $value;— adds to the beginning
- Remove elements:
pop @array;— removes from the endshift @array;— removes from the beginning
🔄 Looping Through an Array
foreach my $color (@colors) {
print "$color\n";
}
Or using a C-style loop:
for (my $i = 0; $i < @colors; $i++) {
print $colors[$i], "\n";
}
📐 Other Handy Array Tricks
- Array size:
$size = scalar @colors; - Last index:
$last_index = $#colors; - Slice of array:
@slice = @colors[0, 2];# gets ‘red’ and ‘blue’ - Sort an array:
@sorted = sort @colors; - Reverse an array:
@reversed = reverse @colors;