My Coding > Programming language > Perl > Perl Hash HowTo

Perl Hash HowTo

Hash in Perl is a set of key-value pairs. Perl hash can have a lot of advantages in compare with array. In Perl, one can use HASH and HASH REFERENCE.

Initialize a hash

Hereinafter I will use %h for hash and $hr - for hash reference

Assigning an empty hash

# hash
 my %h = ();
# hash reference
 my $hr = {};

Assigning non empty hash

Assigning non empty hash for hash

# initializing with key-value pairs via fat arrow
 my %h1 = ("a"=>"alpha", "b"=>"betta", "g"=>"gamma",);

# initializing with fat arrow, ommiting quatas
 my %h2 = (a => "alpha", b => "betta", g => "gamma",);

# initializing with key-value pairs
 my %h3 = ("a", "alpha", "b", "betta", "g", "gamma",);

Assigning non empty hash for hash reference

# initializing with key-value pairs via fat arrow
 my $hr1 = {"a"=>"alpha", "b"=>"betta", "g"=>"gamma",};

# initializing with fat arrow, ommiting quatas
 my $hr2 = {a => "alpha", b => "betta", g => "gamma",};

# initializing with key-value pairs
 my $hr3 = {"a", "alpha", "b", "betta", "g", "gamma",};

Adding pair key-value to hash

# hash
 my %h = ();
 $h{"d"} = "delta";
 $h{"u"} = undef; # undefined value

# hash reference
 my $hr = {};
 $hr->{"d"} = "delta";
 $hr->{"u"} = undef; # undefined value

Clear (or empty) a hash

Removing one element from hash

# removing "element" from HASH
 delete $h{"element"};

# removing "element" from HASH REFERENCE
 delete $hr->{"element"};

Clear (or empty) all hash

There is no tools to clear hash at one movement and we need to remove all elements individually

#emptying HASH
 for (keys %h)
	{ delete $h{$_}; }

#emptying HASH REFERENCE
 for (keys %$hr)
	{ delete $hr->{$_}; }

Hash size

It is possible to count how many elements in hash and how much memory is nesessary for this hash

Number of elements in hash

It is possible to do scalar over the keys of hash or add 0 to convert to numbers

# HASH size
 my %h1 = ("a"=>"alpha", "b"=>"betta", "g"=>"gamma",);
 print 0+keys(%h1); # will be 3
 print scalar keys(%h1); # will be 3

# HASH REFERENCE size
 my $hr1 = {"a"=>"alpha", "b"=>"betta", "g"=>"gamma",};
 print 0+keys(%{$hr1}); # will be 3
 print scalar keys(%{$hr1}); # will be 3

Hash memory size

You need to use module Devel::Size to count memory used

use Devel::Size qw(size total_size);
# HASH memory size
 my %h1 = ("a"=>"alpha", "b"=>"betta", "g"=>"gamma",);
 print total_size( \%h1 ); # will be 423 or arround

# HASH REFERENCE memory size
 my $hr1 = {"a"=>"alpha", "b"=>"betta", "g"=>"gamma", "d"=>"delta",};
 print total_size( $hr1 ); # will be 524 or arround


Published: 2021-09-07 06:45:02
Updated: 2021-09-07 10:37:51

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.