Forum

Notifications
Clear all

Learn Perl Arrays

1 Posts
1 Users
0 Reactions
10 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

 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 end
    • unshift @array, $value; — adds to the beginning
  • Remove elements:
    • pop @array; — removes from the end
    • shift @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;

 


   
Quote
Share: