Add and Remove Elements in Perl Hashes

PERLServer Side ProgrammingProgramming Scripts

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
raja
Published on 29-Nov-2019 05:59:22
Advertisements