Add and Remove Elements in Perl Hashes


Adding a new key/value pair in a Perl hash can be done with one line of code using a simple assignment operator. But to remove an element from the hash you need to use delete function as shown below in the example −

Example

 Live Demo

#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";

# adding an element to the hash;
$data{'Ali'} = 55;
@keys = keys %data;
$size = @keys;
print "2 - Hash size: is $size\n";

# delete the same element from the hash;
delete $data{'Ali'};
@keys = keys %data;
$size = @keys;
print "3 - Hash size: is $size\n";

Output

This will produce the following result −

1 - Hash size: is 3
2 - Hash size: is 4
3 - Hash size: is 3

Updated on: 29-Nov-2019

642 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements