# convert list to hash
%some_hash=('foo',35,'bar',12.4,2.5,'hello','wilma',1.72e30,'betty',"bye\n");
# 上面的语句也相当于hash的初始化了。相当于下面的5行
$some_hash{'foo'} = 35;
$some_hash{'bar'} = 12.4;
$some_hash{'2.5'} = 'hello';
$some_hash{'wilma'} = 1.72e30;
$some_hash{'betty'} = "bye\n";
# 如果list中的元素是奇数个,这个过程会怎样呢?会报错吗?
# 看下面的这个模拟程序
%hash_test = ('a','b',123);
foreach my $key (keys %hash_test){
print "$key => $hash_test{$key}\n";
print "${key}'s value is undefind!\n" unless defined $hash_test{$key};
}
# 在win下直接执行perl xx.pl的结果如下:
123 =>
123's value is undefind!
a => b
# 在win下执行perl -w xx.pl的结果发现,虽然程序没有抛错终止,但是还是给出了warning信息的:
Odd number of elements in hash assignment at test.pl line 1.
Use of uninitialized value in concatenation (.) or string at test.pl line 3.
123 =>
123's value is undefind!
a => b
# convert hash to list
@any_array = %some_hash;
# 这样得到的列表会类似上面的hash赋值用的列表。但是不保证KV对的顺序,因为Perl为了优化哈希,已经对hash进行了特别排序。但KV的对应关系不会被打乱。
哈希赋值引自 访问整个哈希
my %new_hash = %old_hash;
my %inverse_hash = reverse %any_hash; #这个过程会将原来的%any_hash中的KV全部反转过来,赋值到新的%inverse_hash中。这里如果出现%inverse_hash中key重复的情况,后面的会覆盖掉前面的。
my %hash = (a=>1,b=>2,c=>1);
my @keys = keys %hash;
my @values = values %hash;
print 'keys of the %hash are : '."@keys\n";
print 'values of the %hash are : '."@values\n";
my $count1 = keys %hash;
my $count2 = values %hash;
print "scalar form of keys = $count1\n";
print "scalar form of values = $count2\n";
#上面程序的输出结果如下:
keys of the %hash are : c a b
values of the %hash are : 1 1 2 #注意这里重复的value也会按照跟key对应的顺序输出。
scalar form of keys = 3
scalar form of values = 3
##一种不太常见,但是也有使用场景的,对hash判空的操作
if (%hash) {
print '%hash is not empty!';
}
if ( exists $some_hash{"dino"} ) { #注意,虽然$some_hash{"dino"}看上去像是获取dino对应的值,但是这个判读其实跟值没有半毛钱关系,主要是check dion是否作为一个key存在于$some_hash中。
print 'dino exists as a key in $some_hash';
}
delete函数引自 哈希的典型应用
my $person = "betty";
delete $books{$person}; #删除person作为key对应的那条记录
哈希元素内插引自 哈希的典型应用
注意这里所说的是哈希元素的内插,整个哈希元素还不支持内插,这个和list和array有一些区别。
foreach my $person (sort keys %books) {
if ($books{$person}) {
print "$person has $books{$person} items\n";
}
}