FreeKB - Perl (Scripting) Hash (lock_keys lock_values)
Perl (Scripting) - Hash (lock_keys lock_values)

In Perl, there are 3 different kinds of hashes.

  • A regular hash, which is defined by the % and ( ) characters - %hash = ( );
  • A reference hash, which is defined with the $ and { } characters = $hash = { };
  • A hash array, which is defined with the % and [ ] characters - %hash = [ ];


Let's say you have the following hash. In this example, the foo key in the hash is empty.

my %hash = ( 'foo' => '' );


A value can be appended to the employee key, like this.

$hash{foo} = "bar";


Dumper can be used to display the structure of the hash.

use Data::Dumper;
print Dumper \%hash;


Now, the employee key contains a value of John Doe.

$VAR1 = {
           'foo' => 'bar'


The lock_keys and lock_value subroutines can be used to lock the key, so that the value in the key cannot be modified.

use Hash::Util qw (lock_keys unlock_keys lock_value unlock_value);


In this example, every key in the hash is locked, so that no keys can be added, modified, or removed. 

lock_keys (%hash);


The value with the employee key is locked, so that the value cannot be modified or removed.

lock_value(%hash, "foo");


Attempting to modify the value of a locked key value pair . . .

$hash{foo} = "Hello World";


. . . will produce the following.

Modification of a read-only value attempted


The value can be unlocked.

unlock_value(%hash, "foo");


Every key in the hash can be unlocked, so that keys can be added, modified, or removed. 

unlock_keys (%hash);

Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 74478 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |