Bootstrap FreeKB - Perl (Scripting) - Define a hash
Perl (Scripting) - Define 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 = { };

Here are different ways to create an empty hash named "hash".

my %hash;
my %hash = ();

 

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

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

 

Which should produce the following.

$VAR1 = {};

 

Keys that contain no values (empty keys) can be created like this.

%hash = (
  foo => "", 
  bar => ""
);

 

Or, like this.

$hash{foo} = undef;
$hash{bar} = undef;

 

Or, like this.

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

 

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

print Dumper \%hash;

 

Which will display the data structure of the hash.

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

 

Let's say you want to create a hash that has two (or more) keys, like this. In this example, the bar key is a child of the foo key, meaning this hash is multidimensional.

'foo' {
        'bar' => 'Hello World'
      }

 

Here is how you can create the multidimensional keys and value.

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

 

Or like this.

my $hash{foo}->{bar} = "Hello World";

 

Dumper can be used to print the hash.

print Dumper \%hash;

 

Which will produce the following.

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

 

Or to print the value of the bar key.

print $hash{foo}->{bar};

 

Which will produce the following.

Hello World

 




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