PERL Hash

PERL Hash are associative array i.e. arrays with a string for an index.


HASH Assignment and access:


use Data::Dumper;


my @array = qw(k3v1 k3v2 k3v3 k3v4);

%my_hash = (

"k1" => {"k1v1","k1v2","k1v3","k1v4"},

"k2" => ["k2v1","k2v2","k2v3","k2v4"],

"k3" => [@array],

);


print "\n PRINTING HASH -> KEY1 \n";

print Dumper $my_hash{k1};


print "\n PRINTING ARRAY IN KEY2 \n";

print "@{$my_hash{k2}}\n";


print "\n PRINTING ENTIRE HASH \n";

print Dumper \%my_hash;



  • CONSOLE OUTPUT:

  • >> perl hashexp.pl


  • PRINTING HASH KEY1

  • $VAR1 = {

  • 'k1v3' => 'k1v4',

  • 'k1v1' => 'k1v2'

  • };


  • PRINTING ARRAY IN KEY2

  • k2v1 k2v2 k2v3 k2v4


  • PRINTING ENTIRE HASH

  • $VAR1 = {

  • 'k2' => [

  • 'k2v1',

  • 'k2v2',

  • 'k2v3',

  • 'k2v4'

  • ],

  • 'k1' => {

  • 'k1v3' => 'k1v4',

  • 'k1v1' => 'k1v2'

  • },

  • 'k3' => [

  • 'k3v1',

  • 'k3v2',

  • 'k3v3',

  • 'k3v4'

  • ]

  • };


Passing HASH from one script to another

use strict;

use warnings;


use Data::Dump qw(dump);


# Create a complex structure

my %hash = (

number => 42,

string => 'This is a string',

array => [ 1 .. 10 ],

hash => { apple => 'red', banana => 'yellow' },

);

# See what it looks like

print "Here is the structure before dumping to file:\n";

dump \%hash;


# Print structure to file

open my $out, '>', 'dump_struct' or die $!;

print {$out} dump \%hash;

close $out;


# Read structure back in again

open my $in, '<', 'dump_struct' or die $!;

our %data;

{

local $/; # slurp mode

%data = %{eval <$in>};

}

close $in;

# See what the structure read in looks like

print "Here is the structure after reading from file:\n";

dump \%data;

__END__

PUSH Values to an array

To push values to an array i,e, key -> value array

push @{ $hash{$key1}{$key2} }, $valuse;