hash 和hash引用的常见操作方法

hash和hash引用的常见操作方法如下:

#init a hash 
my %hash = ();

#init a hash reference 
my $hash_ref = {};

# add a key/value pair to hash
$hash{"key01"} = '111';
$hash{"key02"} = '222';

$hash_ref->{"key01"} = "333";
$hash_ref->{"key02"} = "444";

# loop hash array
while (my ($key, $value) = each(%hash)){
    print "$key => $value\n";
}

print "\n";

while (my ($key, $value) = each(%$hash_ref)){
    print "$key => $value\n";
}
print "\n";

#get hash size-ref

print "hash size : ", scalar(keys(%hash)),"\n";
print "hash ref size: ", scalar(keys %$hash_ref),"\n";

运行结果:

key02 => 222
key01 => 111

key02 => 444
key01 => 333

hash size : 2
hash ref size: 2

更多操作方法可以参加Perl Hash How to

posted @ 2018-01-07 22:21  小怪兽&奥特曼  阅读(143)  评论(0编辑  收藏  举报