微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Perl Learning - 10 (hash)

Hash is the one that makes Perl one of the most popular programer languages.
It's another data structure similar to array.
 
Hash is indexed by keys,each key is an uniq characters but not number array uses.
The keys have no order the numbers in array have.
 
Each key matches a value,keys must be uniq while values don't have to.
Keys are characters,but values can be any kind of scalars.
 
The way to access hash element: $hash{$some_key}
 
$family_name{"fred"}="flintstone";
$family_name{"barney"}="rubble";
 
foreach $person(qw<barney fred){
 print "I've heard of $person $family_name{$person}.\n";
}
 
Hash has its own name space separated from scalar,array and subroutine.
Perl kNows those things with same name,however we had better not use same name for different data types.
 
The key of hash can be any kind of expressons:
 
$foo="bar";
print $family_name{$foo."ney"}; # "rubble"
 
Giving a value to an existed key,the original one will be covered:
 
$family_name{"fred"}="astaire"; # new value
$bedrock=$family_name{"fred"}; # "astaire"
 
Accessing non-existed hash element will get undef.
 
We can give a list to a hash,or give a hash to a list:
 
%some_hash=("foo",35,"bar",12.4,2.5,"hello","wilma",1.72e30,"betty","bye\n");
@any_array=%some_hash;
 
The number of elements given to a hash must be even.
The order of @any_array usually is different from %some_hash. Hash doesn't care the order.
 
Like array,hash can be reversed,the key and value replaces each other.
 
%inverse_hash=reverse %any_hash;
 
To easily find out which are keys and which are values,we use "=>" in hashes.
 
my %last_name=(
 "fred"   => "flintstone",
 "dino"   => "undef",
 "barney" => "rubble",
 "betty"  => "rubble",
 );
my @array=%last_name;
print "@array\n";

 
The last ',' ins't a must but recommended,since it will be better when adding new elemens to the hash.
Perl will check all the ',' and the last one.
 
"=>" is almost same as ',' the different is that words on the left of a '=>' is automatically "" quoted.
So the keys on the left of "=>" don't have to be quoted,the keys in $hash{ } don't have to be quoted either.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐