加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl Learning - 10 (hash)

发布时间:2020-12-15 21:02:29 所属栏目:大数据 来源:网络整理
导读: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 numbe
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","byen");
@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 "@arrayn";

?
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读