您的位置:首页 > 其它

Perl Learning - 10 (hash)

2012-11-13 14:41 337 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: