Bootstrap FreeKB - Perl (Scripting) - Remove values from an array in a hash
Perl (Scripting) - Remove values from an array 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 = { };

In this example, the foo key is an array that contains two values, Hello and World.

my %hash = ( 'foo' => [ 'Hello', 'World' ] );

 

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

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

 

Which shows that the foo key array contains two values, Hello and World.

$VAR1 = {
          'foo' => [ 
                     'Hello', 
                     'World'
                   ]
        };

 

All of the values in the foo key array can be removed, 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 array is now empty.

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

 


Multidimensional array

In this example, the departments_key array is a child of the employees_key array.

my %hash = ( 'employees_key' => [ { 'departments_key' => [ 'engineering', 'sales' ] } ] );

 

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

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

 

Which shows that department_key contains now values, engineering and sales.

$VAR1 = {
          'employees_key' => [
                              {
                               'departments_key' => [
                                                     'engineering',
                                                     'sales'
                                                    ],
                              }
                             ]
        };

 

Here is now to undefine departments_key.

foreach my $employees_key (@{$hash{employees_key}}) {
  undef $employees_key->{departments_key};
}

 

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

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

 

Which shows that departments_key is now undefined.

$VAR1 = {
          'employees_key' => [
                              {
                               'departments_key' => undef
                              }
                             ]
        };



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