Introduction to Arrays
Arrays are a fundamental data structure in Perl that allow you to store and manipulate a collection of scalar values. They are especially useful for handling lists of data, where you might want to perform operations on multiple items at once.
What is an Array?
An array in Perl is an ordered list of scalar values. Each value in an array is called an element, and each element has an index, which is its position in the array. In Perl, array indices start at 0.Declaring and Initializing Arrays
You can declare an array in Perl using the@
symbol. Here's how to create and initialize an array:`
perl
my @fruits = ('apple', 'banana', 'cherry');
`
In the above example, @fruits
is an array containing three elements: 'apple', 'banana', and 'cherry'.
Accessing Array Elements
To access an individual element in an array, you use the array name followed by the index in square brackets. For example:`
perl
print $fruits[0];
Outputs: apple
print $fruits[1];Outputs: banana
`
Modifying Array Elements
You can also modify elements of an array by assigning a new value to a specific index:`
perl
$fruits[1] = 'blueberry';
print $fruits[1];
Outputs: blueberry
`
Array Operations
Perl provides a variety of built-in functions that you can use to manipulate arrays. Here are some of the most common operations:Adding Elements
You can add elements to the end of an array using thepush
function:`
perl
push(@fruits, 'date');
print join(', ', @fruits);
Outputs: apple, blueberry, cherry, date
`
Removing Elements
To remove the last element from an array, you can use thepop
function:`
perl
my $last_fruit = pop(@fruits);
print $last_fruit;
Outputs: date
`
Getting the Size of an Array
You can find out how many elements are in an array using thescalar
function:`
perl
my $size = scalar(@fruits);
print $size;
Outputs: 3
`
Iterating Over Arrays
A common operation with arrays is to iterate over their elements. You can use aforeach
loop for this:`
perl
foreach my $fruit (@fruits) {
print $fruit . "\n";
}
`
Practical Example
Let's put everything together in a practical example. Suppose you want to manage a shopping list:`
perl
my @shopping_list = ('milk', 'eggs', 'bread');
Adding an item
push(@shopping_list, 'butter');Removing the last item
my $removed_item = pop(@shopping_list);Displaying the shopping list
print "Current shopping list:\n"; foreach my $item (@shopping_list) { print "- $item\n"; }`
This example demonstrates how to create an array, modify it, and iterate over its elements to display them.