hashes in perl
In Perl, a hash is a variable that can hold an unordered collection of key-value pairs, similar to a dictionary in Python or an associative array in other programming languages. Hashes are denoted by the %
sigil, and can be declared using the my
keyword. Here's an example:
my %ages = ("Alice" => 25, "Bob" => 30, "Charlie" => 35); # declare a hash of names and ages
Hash keys and values can be of any scalar type, including strings, numbers, and references. To access individual values in a hash, you can use the key as an index in curly braces ($hash{key}
). For example:
my %ages = ("Alice" => 25, "Bob" => 30, "Charlie" => 35); print $ages{"Alice"}; # prints 25 print $ages{"Charlie"}; # prints 35
You can also modify individual values in a hash by assigning a new value to the corresponding key:
my %ages = ("Alice" => 25, "Bob" => 30, "Charlie" => 35); $ages{"Alice"} = 26; print %ages; # prints "Alice" => 26, "Bob" => 30, "Charlie" => 35
In addition to accessing individual values in a hash, you can also loop over all the keys and values using the keys
and values
functions. For example:
my %ages = ("Alice" => 25, "Bob" => 30, "Charlie" => 35); foreach my $name (keys %ages) { my $age = $ages{$name}; print "$name is $age years old\n"; }
In summary, hashes in Perl are used to hold an unordered collection