FreeKB - Perl (Scripting) Hash Array (remove values)
Perl (Scripting) - Hash Array (remove 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 = [ ];

 

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
                              }
                             ]
        };


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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |