How do I work with arrays and hashes in Perl

In Perl, arrays and hashes are essential data structures that allow you to group and manage collections of data efficiently.

Working with Arrays

Arrays in Perl are ordered lists that can store scalars (numbers, strings, etc.). You can use various functions to manipulate arrays.

Example:

# Declaring an array @fruits = ("apple", "banana", "cherry"); # Accessing an element print $fruits[1]; # Outputs: banana # Adding an element push(@fruits, "orange"); # Looping through the array foreach my $fruit (@fruits) { print $fruit; }

Working with Hashes

Hashes are key-value pairs, which allow for easy data retrieval using unique keys. Hashes are unordered collections.

Example:

# Declaring a hash %ages = ("Alice" => 30, "Bob" => 25, "Charlie" => 35); # Accessing a value print $ages{"Bob"}; # Outputs: 25 # Adding a key-value pair $ages{"David"} = 20; # Looping through the hash while (my ($name, $age) = each %ages) { print "$name is $age years old"; }

Perl arrays hashes data structures scalars key-value pairs