一個 function
sub foo {
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( ‘:’ );
$HoH{ $login }{ ‘uid’ } = $uid;
$HoH{ $login }{ ‘gid’ } = $gid;
$HoH{ $login }{ ‘dir’ } = $dir;
}
close PASSWD;
return \%HoH;
}
my $aaa = &foo();
這時 print $aaa 會看到它是個 HASH
我如果
print “$key $value “;
}
會出現 帳號 + hash
htt HASH(0x8758e5c)
daemon HASH(0x8752f54)
我們也可以
use Data::Dumper;
print Dumper($aaa);
就會顯示
‘lawrence’ => {
‘uid’ => ‘10011’,
‘dir’ => ‘/home/lawrence’,
‘gid’ => ‘10014’
},
‘bin’ => {
‘uid’ => ‘1’,
‘dir’ => ‘/bin’,
‘gid’ => ‘1’
},
‘mailnull’ => {
‘uid’ => ’47’,
‘dir’ => ‘/var/spool/mqueue’,
‘gid’ => ’47’
},
我如果要取 ‘/home/lawrence’ 這個值
print $aaa->{lawrence}->{dir}
參考: http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/hash/ 的 Function to build a hash of hashes; return a reference
Access and print a reference to a hash of hashes 的顯示方式
my $rHoH = foo();
my( $uid, $gid, $dir );
for my $login ( keys %$rHoH ) {
$uid = $rHoH->{ $login }->{ ‘uid’ }; # method 1 most readable
$gid = ${ $rHoH->{ $login } }{ ‘gid’ }; # method 2
$dir = ${ ${ $rHoH }{ $login } }{ ‘dir’ }; # method 3 least readable
print “uid: $uid, gid: $gid, dir, $dir.
“;
}
留言