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
In Perl, a hash (also known as an associative array) is a collection of key-value pairs. The key is unique, and its associated value can be a scalar, another hash, an array, or more complex data structures. This tutorial will cover some of the fundamental hash functions in Perl.
A hash is defined using parentheses ()
, and it associates keys with values using the =>
fat comma.
my %hash = ( 'apple' => 'fruit', 'carrot' => 'vegetable', );
To access a value from a hash, use the key:
print $hash{'apple'}; # Outputs: fruit
To modify a value, just assign a new value to the key:
$hash{'apple'} = 'delicious fruit';
Adding a new key-value pair is as simple as assigning a value to a new key:
$hash{'orange'} = 'citrus fruit';
Use the delete
function to remove a key-value pair:
delete $hash{'apple'};
The exists
function checks if a key exists in a hash:
if (exists $hash{'apple'}) { print "'apple' exists in the hash\n"; }
keys
: Returns a list of all keys in the hash.values
: Returns a list of all values in the hash.my @all_keys = keys %hash; my @all_values = values %hash;
When a hash is used in a list context, it returns a list of its key-value pairs:
my %new_hash = ('a' => 1, 'b' => 2); my @array = %new_hash; # @array is now ('a', 1, 'b', 2)
each
FunctionThe each
function returns a 2-element list of the next key-value pair:
while (my ($key, $value) = each %hash) { print "$key => $value\n"; }
You can access multiple values at once using a slice:
@values = @hash{'apple', 'orange'};
Find out the number of key-value pairs in a hash using a scalar context:
my $number_of_pairs = scalar keys %hash;
Merge two hashes by using the (%hash1, %hash2)
syntax:
my %hash1 = ( 'a' => 1, 'b' => 2 ); my %hash2 = ( 'b' => 3, 'c' => 4 ); my %merged = (%hash1, %hash2); # %merged is ('a' => 1, 'b' => 3, 'c' => 4)
Note that if keys overlap, the value from %hash2
will overwrite the value from %hash1
.
Hashes are incredibly versatile in Perl, allowing for efficient storage and lookup of key-value pairs. By understanding the various hash functions and operations, you can make the most of this powerful data structure in your Perl scripts.
Creating and initializing hashes in Perl:
# Creating an empty hash my %person; # Initializing a hash with key-value pairs my %employee = ('name' => 'Alice', 'age' => 30, 'department' => 'HR');
Adding and deleting key-value pairs in Perl hashes:
my %student = ('name' => 'Bob', 'age' => 25); # Adding a new key-value pair $student{'grade'} = 'A'; # Deleting a key-value pair delete $student{'age'};
Iterating over keys and values in Perl hashes:
foreach
.my %car = ('make' => 'Toyota', 'model' => 'Camry', 'year' => 2020); # Iterating over keys foreach my $key (keys %car) { print "Key: $key\n"; } # Iterating over values foreach my $value (values %car) { print "Value: $value\n"; }
Merging and updating hashes in Perl:
merge
and assignment.my %employee = ('name' => 'Alice', 'age' => 30); my %department = ('department' => 'HR', 'location' => 'Office'); # Merging hashes my %merged = (%employee, %department); # Updating a hash $employee{'age'} = 31;
Sorting hashes in Perl:
sort
.my %grades = ('Alice' => 'A', 'Bob' => 'B', 'Charlie' => 'C'); # Sorting by keys foreach my $key (sort keys %grades) { print "$key: $grades{$key}\n"; } # Sorting by values foreach my $name (sort { $grades{$a} cmp $grades{$b} } keys %grades) { print "$name: $grades{$name}\n"; }
Checking for key existence in Perl hashes:
my %colors = ('red' => 1, 'green' => 1, 'blue' => 1); # Checking for key existence if (exists $colors{'green'}) { print "Green color exists.\n"; }
Hash functions for counting and filtering in Perl:
my %fruits = ('apple' => 3, 'banana' => 5, 'orange' => 2); # Counting elements my $total_fruits = keys %fruits; # Filtering elements my %filtered_fruits = grep { $fruits{$_} > 2 } keys %fruits;
Deep copying hashes in Perl:
Storable
module.use Storable qw(dclone); my %original_hash = ('key1' => {'nested' => 'value1'}, 'key2' => {'nested' => 'value2'}); # Creating a deep copy my %copied_hash = %{ dclone(\%original_hash) };