Perl哈希学习

Hash是一种结构。

key/value.

访问hash元素

$hash{$some_key}

当给hash选择名字时,最好这样思考:hash元素的名字和key之间可以用for来连接。如 the family_name for fred is flintstone.

要引用整个hash,使用百分号(%)作为前缀。

 

#!/bin/perl

use warnings;
use strict;

my $person;
my %family_name;

$family_name{"fred"} = "flintstone";
$family_name{"barney"} = "rubble";

foreach $person(qw< barney fred>) {
 print "I've heard of $person $family_name{$person}./n";
}


my %some_hash = ("foo", 35, "bar", 12.4, 25, "hello", "wilma", 1.72e30, "betty", "bye/n");

my @array_array = %some_hash;
print "@array_array/n";

 

哈希赋值方法 大箭头符号 (=>)

 

my %last_name = (
 "fred" => "flintstion",
 "dino" => undef,
 "barney" => "rubble",
 "betty" => "rubble",
);

 

keys函数会返回此hash的所有keys, values含税将返回所有的values。如果hash中没有元素,则此函数将返回空列表。

 

my @k = keys %last_name;
my @v = values %last_name;
my $count = keys %last_name; #scalar-producing, key/value pairs

 

print "the key are @k./n";
print "the value are @v./n";
print "the count are $count./n";

 

each函数

如果想迭代得到hash中的每个元素,一个通常的方法是使用each函数,它将返回key/value对的元素对。当对同一个hash函数进行一次迭代时,将返回下一个key/value对,直到所有的元素均被访问。

my $key;
my $value;

 

while (($key, $value) = each %last_name) {

#foreach (($key, $value) = each %last_name) {
 print "$key => $value./n";
}

注意两种循环的结果,原因在于两种循环的设计机制不同。

 

foreach $key (sort keys %last_name) {
 $value = $last_name{$key};
 print "$key => $value./n";
 print "$key => $last_name{$key}./n";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值