Bootstrap FreeKB - Perl (Scripting) - Remove value from a key in a hash
Perl (Scripting) - Remove value from a key 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 contains a value of bar.

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

 

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

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

 

Which shows that the foo key contains a value of bar.

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

 

The value can be removed from the foo key, like this.

$hash{foo} = "";

 

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

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

 

Which shows that the foo key is now empty (contains no value).

$VAR1 = {
           'foo' => ''
        };

 

Let's say you have the following hash. In this example, the bar key is a child of the foo key, meaning the hash is multidimensional.

my %hash = ( 'foo' => { 'bar' => 'Hello World' } );

 

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

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

 

Which shows that the bar key contains a value of John Doe.

$VAR1 = {
           'foo' => {
                      'bar' => 'Hello World'
                    }
        };

 

A value can be removed from bar, like this.

$hash{foo}->{bar} = "";

 

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

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

 

Which shows that the bar key now contains no value.

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

 




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 15633c in the box below so that we can be sure you are a human.