Wednesday 2 December 2009

Hash of Hashes

Create a hash of hashes via references:

The following two solutions are equivalent, except for the way the look.

Solution 1 :

$requiredPatches_href->{ $patch }->{ os } = $os;
$requiredPatches_href->{ $patch }->{ arch } = $arch;
$requiredPatches_href->{ $patch }->{ info } = $info;

Solution 2 : ( It is much clearer)

$requiredPatches_href->{ $patch } = {
os => $os,
arch => $arch,
info => $info,

};


Here is a small program to extract users their login name, uid,homedir and gid from /etc/passwd using HashOfHashes and hash reference:


#!/usr/bin/perl -w

sub func
{
my ( $login, $p, $uid, $gid, $gecos, $dir, $s );
my %HoH = ();
my $file = '/etc/passwd';
open( PASSWD, "lt; $file" ) or die "Can't open $file : $!";
while( <passwd> )
{
( $login, $p, $uid, $gid, $gecos, $dir, $s ) = split( ':' );
#writing a hash of hash using reference
$HoH{$login} = {
'uid' => $uid,
'gid' => $gid,
'dir' => $dir,
};
}
close PASSWD;
return \%HoH;

}
my $hash_ref = &func;

# Print the keys and values of a hash, given a hash reference

while( my ($k, $v) = each %$hash_ref )
{
# Print Outer hash HOH keys and values
print "login: $k ";
# Print Inner hash keys and values for each outer hash key i.e login name
while ( my ($key,$val) = each %$v )
{
print "$key:$val ";
}
print "\n";
}

Output looks like this:

login: bin uid:2 dir:/bin gid:2
login: clamav uid:110 dir:/var/lib/clamav gid:120
login: nobody uid:65534 dir:/nonexistent gid:65534
login: lp uid:7 dir:/var/spool/lpd gid:7


No comments:

Post a Comment

Tweets by @sriramperumalla