一個 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

我如果

while (my ($key,$value) = each %$aaa) {
print “$key $value “;
}

會出現 帳號 +  hash

root HASH(0x873cd40)
htt HASH(0x8758e5c)
daemon HASH(0x8752f54)

我們也可以
use Data::Dumper;
print Dumper($aaa);

就會顯示

$VAR1 = {
‘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.
“;
}

 

Related posts 相關文章
2020 年迎來了 PHP 8 與 Perl 7
More...
安裝 perl 5.8.1 版本 – 草記
More...
perl 備註
More...
perl 隨機產生 password 密碼
More...

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。