Bootstrap FreeKB - Perl (Scripting) - Lock keys and values in a hash
Perl (Scripting) - Lock keys and values in a hash

Updated:   |  Perl (Scripting) articles

In Perl, there are 2 different kinds of hashes.

  • A hash, which is defined by the % and ( ) characters - %hash = ( );
  • A reference hash, 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 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);



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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