Perl Hashes

The hashes is the most essential and influential part of the perl language. A hash is a group of key-value pairs. The keys are unique strings and values are scalar values.

Hashes are declared using my keyword. The variable name starts with a (%) sign.

Hashes are like arrays but there are two differences between them. First arrays are ordered but hashes are unordered. Second, hash elements are accessed using its value while array elements are accessed using its index value.

No repeating keys are allowed in hashes which makes the key values unique inside a hash. Every key has its single value.

Syntax:

snippet
my %hashName = (
	"key" => "value";
)

Perl Hash Accessing

To access single element of hash, ($) sign is used before the variable name. And then key element is written inside {} braces.

snippet
my %capitals = (
    "India"  => "New Delhi",
    "South Korea" => "Seoul",
    "USA"  => "Washington, D.C.",
    "Australia"  => "Canberra"
);
print"$capitals{'India'}\n";
print"$capitals{'South Korea'}\n";
print"$capitals{'USA'}\n";
print"$capitals{'Australia'}\n";

Output:

Output
New Delhi Seoul Washington, D.C. Canberra

Perl Hash Indexing

Hashes are indexed using $key and $value variables. All the hash values will be printed using a while loop. As the while loop runs, values of each of these variables will be printed.

snippet
my %capitals = (
    "India"  => "New Delhi",
    "South Korea" => "Seoul",
    "USA"  => "Washington, D.C.",
    "Australia"  => "Canberra"
);
# LOOP THROUGH IT
while (($key, $value) = each(%capitals)){
     print $key.", ".$value."\n";
}

Output:

Output
Australia, Canberra India, New Delhi USA, Washington, D.C. South Korea, Seoul

Perl sorting Hash by key

You can sort a hash using either its key element or value element. Perl provides a sort() function for this. In this example, we'll sort the hash by its key elements.

snippet
my %capitals = (
    "India"  => "New Delhi",
    "South Korea" => "Seoul",
    "USA"  => "Washington, D.C.",
    "Australia"  => "Canberra"
);
# Foreach loop
foreach $key (sort keys %capitals) {
     print "$key: $capitals{$key}\n";
}

Output:

Output
Australia: Canberra India: New Delhi South Korea: Seoul USA: Washington: D.C.

Look at the output, all the key elements are sorted alphabetically.

Perl sorting Hash by its value

Here we'll sort hash by its value elements.

snippet
my %capitals = (
    "India"  => "New Delhi",
    "South Korea" => "Seoul",
    "USA"  => "Washington, D.C.",
    "UK"  => "London"
);
# Foreach loop
foreach $value (sort {$capitals{$a} cmp $capitals{$b} }
           keys %capitals)
{
     print "$value $capitals{$value}\n";
}

Output:

Output
UK London India New Delhi South Korea Seoul USA Washington D.C.

Look at the output, all the value elements are sorted alphabetically.

Perl Hash key Existence

Accessing a key-value pair from hash which doesn't exist will return error or warnings. To prevent from this, you can check whether a key exist or not in a hash with exists() function. It returns true if the key exists.

snippet
my %capitals = (
    "India"  => "New Delhi",
    "South Korea" => "Seoul",
    "USA"  => "Washington, D.C.",
    "Australia"  => "Canberra"
);
if (exists($capitals{'India'}))
{
  print "found the key\n";
}

Output:

Output
found the key

The above output shows that the 'Indis' key exists in the 'capitals' hash.

Perl Hash Slices

If you want only some values from a hash, you can extract them and display as a list of values.

For this, you have to store them in an array variable with @ prefix as they will return a list of values and then print them.

snippet
my %capitals = (
    "India"  => "New Delhi",
    "South Korea" => "Seoul",
    "USA"  => "Washington, D.C.",
    "Australia"  => "Canberra"
);
@array = @capitals{India, USA, Australia};
print "@array\n";

Output:

Output
New Delhi Washington, D.C. Canberra

Perl Hash creating Empty hash

An empty hash will always have size 0.

In this example, first we have created a hash with size 3. Then we have created an empty hash with size 0.

snippet
my %first = ('john'=>9853147320, 'jose'=>7823654028, 'janie',=>'8850279610');  
print 'hash size: ', scalar keys %first;  
print "\n";  
#creating emptyempty hash  
my %empty=();  
print 'hash size: ', scalar keys %empty;

Output:

Output
hash size: 3 hash size: 0

Perl Adding Hash Elements

New key-value pair can be added in a hash by declaring them as single element in the hash variable.

Here, we are adding two key-value pair, [Germany - Berlin] and [UK - London].

snippet
my %capitals = (
    "India"  => "New Delhi",
    "South Korea" => "Seoul",
    "USA"  => "Washington, D.C.",
    "Australia"  => "Canberra"
);
while (($key, $value) = each(%capitals)){
     print $key.", ".$value."\n";
}
#adding new element
$capitals{Germany} = Berlin;
$capitals{UK} = London;
# Printing new hash
print "\n";
while (($key, $value) = each(%capitals)){
     print $key.", ".$value."\n";
}

Output:

Output
UK, London Australia, Canberra Germany, Berlin India, New Delhi USA, Washington D.C. South Korea, Seoul

Perl Removing Hash Elements

To remove a hash element, use delete() function.

Here, we have removed both the key-value pairs which were added in the last example.

snippet
my %capitals = (
    "India"  => "New Delhi",
    "South Korea" => "Seoul",
    "USA"  => "Washington, D.C.",
    "Australia"  => "Canberra"
    "Germany "  => " Berlin"
    " UK "  => "London"
);
while (($key, $value) = each(%apitals)){
     print $key.", ".$value."\n";
}
#removing element
delete($capitals{Germany});
delete($capitals{UK});
# Printing new hash
print "\n";
while (($key, $value) = each(%capitals)){
     print $key.", ".$value."\n";
}

Output:

Output
Australia, Canberra India, New Delhi USA, Washington D.C. South Korea, Seoul

Perl deleting Vs Undefining Hash Elements

deleting: In deleting, key-value pair will be deleted from the hash.

Syntax:

snippet
delete($hash{$key});

undef: In undef, the value will be undefined but key will remain in the hash.

Syntax:

snippet
Undef $hash{$key};

In the following example, we have created a hash 'rank'. One by one we'll undefine and remove all the key values from the hash. On undefining a key only its value will be shown, on deleting a key it will be completely deleted from the hash along with its value.

Like this, at the end all the hash elements will be deleted.

snippet
# creating hash
$rank{'John'} = '5 ';
$rank{'Ana'} = '7 ';
$rank{'Jiyaa'} = '3 ';
$rank{'Jassi'} = '1 ';
# printing all elements in the hash
print "before:\n";
print %rank;
print"\n";
# undefining John in the hash
print "\nundefine John\n";
undef$rank{'John'};
print %rank;
print"\n";
# deleting the 'John' key the in hash element
print "\nremove John\n";
delete($rank{'John'});
print %rank;
print"\n";
# undefining Ana in the hash
print "\nundefine Ana\n";
undef$rank{'Ana'};
print %rank;
print"\n";
# deleting the 'Ana' key the in hash element
print "\nremove Ana\n";
delete($rank{'Ana'});
print %rank;
print"\n";
# undefining Jiyaa in the hash
print "\nundefine Jiyaa\n";
undef$rank{'Jiyaa'};
print %rank;
print"\n";
# deleting the 'Jiyaa' key the in hash element
print "\nremove Jiyaa\n";
delete($rank{'Jiyaa'});
print %rank;
print"\n";
# undefining Jassi in the hash
print "\nundefine Jassi\n";
undef$rank{'Jassi'};
print %rank;
print"\n";
# deleting the 'Jassi' key the in hash element
print "\nremove Jassi\n";
delete($rank{'Jassi'});
print %rank;

Output:

Output
before: John5 Jassi1 Jiyaa3 Ana7 undefine John JohnJassi1 Jiyaa3 Ana7 remove John Jassi1 Jiyaa3 Ana7 undefine Ana Jassi1 Jiyaa3 Ana remove Ana Jassi1 Jiyaa3 undefine Jiyaa Jassi1 Jiyaa remove Jiyaa Jassi1 undefine Jassi Jassi remove Jassi
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents