Perl Tutorial
Fundamentals
Input and Output
Control Flow
Arrays and Lists
Hash
Scalars
Strings
Object Oriented Programming in Perl
Subroutines
Regular Expressions
File Handling
Context Sensitivity
CGI Programming
Misc
Arrays are fundamental structures in Perl that allow you to store ordered lists of scalar values. They are versatile and support a range of operations that make manipulating data straightforward.
Here's a tutorial on arrays in Perl:
You can define an array in Perl by assigning a list of values to an array variable, which is denoted by the @
symbol.
my @fruits = ("apple", "banana", "cherry", "date");
Array elements can be accessed using their index, with 0 being the index of the first element.
print $fruits[0]; # prints "apple" print $fruits[2]; # prints "cherry"
push: Add one or more elements to the end of an array.
push @fruits, "elderberry";
unshift: Add one or more elements to the beginning of an array.
unshift @fruits, "apricot";
pop: Remove and return the last element from the array.
my $last_fruit = pop @fruits;
shift: Remove and return the first element from the array.
my $first_fruit = shift @fruits;
Find out the number of elements in an array using the scalar context.
my $num_fruits = scalar @fruits;
You can extract a sublist from an array using a slice:
my @sublist = @fruits[1, 2]; # gets ("banana", "cherry")
You can use a foreach
loop to iterate over each element:
foreach my $fruit (@fruits) { print "$fruit\n"; }
Arrays can be modified directly using their indices:
$fruits[1] = "blueberry";
You can combine arrays using the list concatenation:
my @vegetables = ("carrot", "broccoli"); my @food = (@fruits, @vegetables);
@_
: Default array variable for passed subroutine parameters.
$#array_name
: Last index of the array. Useful for accessing the last element or determining the size of an array (size = $#array + 1
).
Use strict and warnings: Always start your Perl scripts with use strict;
and use warnings;
. This will help catch common mistakes.
Iterate with foreach: It's generally clearer and less error-prone to iterate over arrays with foreach
than using a traditional for
loop and indices.
Lexical Variables: Use my
to declare lexical variables, which are restricted in scope to the enclosed block, rather than global variables.
In conclusion, arrays in Perl offer a dynamic way to handle ordered collections of data. The built-in functions and flexibility provided by Perl make array handling and manipulation both efficient and straightforward.
Creating and initializing arrays in Perl:
# Creating and initializing arrays my @numbers = (1, 2, 3, 4, 5); my @fruits = qw(Apple Orange Banana);
Accessing elements in Perl arrays:
my @colors = ('Red', 'Green', 'Blue'); my $first_color = $colors[0]; # Accessing the first element print "First color: $first_color\n";
Adding and removing elements from Perl arrays:
my @names = ('Alice', 'Bob', 'Charlie'); # Adding elements push @names, 'David'; # Removing elements pop @names;
Perl array functions and operations:
my @numbers = (3, 1, 4, 1, 5, 9, 2); # Array functions my $count = scalar @numbers; # Count elements my $sum = sum @numbers; # Sum elements (using List::Util) # Array operations my @sorted_numbers = sort @numbers;
Multidimensional arrays in Perl:
# Creating a 2D array my @matrix = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] ); # Accessing elements my $value = $matrix[1][2]; # Accessing element at row 1, column 2
Sorting and searching in Perl arrays:
my @scores = (75, 92, 84, 65, 78); # Sorting my @sorted_scores = sort @scores; # Searching my $index = grep { $scores[$_] == 84 } 0..$#scores;
Perl array slices and splicing:
my @colors = ('Red', 'Green', 'Blue', 'Yellow'); # Array slices my @subset = @colors[1..2]; # Splicing splice @colors, 1, 2, 'Orange', 'Purple';
Iterating through arrays in Perl:
my @days_of_week = qw(Monday Tuesday Wednesday Thursday Friday); # Using foreach loop foreach my $day (@days_of_week) { print "Day: $day\n"; } # Using for loop for my $i (0..$#days_of_week) { print "Day $i: $days_of_week[$i]\n"; }
Perl associative arrays (hashes):
# Creating and initializing a hash my %person = ( 'name' => 'Alice', 'age' => 30, 'city' => 'Wonderland' ); # Accessing values my $name = $person{'name'};