Thursday, 15 October 2009

Perl Hash of Hashes demo

I want to extract users and their uid,gid and home dir and print each of them corresponding to user from /etc/passwd file. This is how we can do:

#!/usr/bin/perl

sub func
{
my ( $login, $p, $uid, $gid, $gecos, $dir, $s );
my %HoH = ();
my $file = '/etc/passwd';
open( PASSWD, "< $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 Outer hash keys and take values(Inner hash)

while( my ($k, $v) = each %$hash_ref )
{
print "login: $k ";

# Print Inner hash keys and values

while ( my ($key,$val) = each %$v )
{
print "$key:$val ";
}
print "\n";
}


O/p:

login: sriram uid:101 dir:/home/sriram gid:102
login: jadu uid:9 dir:/home/jadu gid:9
login: kiran uid:100 dir:/home/krian gid:101
login: vikas uid:109 dir:/home/vikas gid:65534

No comments:

Post a Comment

Tweets by @sriramperumalla