哈希 : 一种数据结构,和数组的相同之处在于:可以容纳很多值,并能随机存取,
区别在于:不像数组是以数字来检索,哈希是以名字来检索。是保证唯一的字符串。
键:其实就是字符串,这些键可以使热河字符串
访问哈希元素:$hash{$some_key} 要用花括号。
访问整个哈希:用%作为前缀,指代整个哈希。
each :罗列哈希的每个键/值对,常见的写法就是使用each,它能用两个元素的列表形式返回键值。
exists:检查哈希中是否有某个键,可以使用exists函数,返回真或假,分别表示键存在与否,和键对应的值无关。
delete:从哈希中删除指定的键,及其相对应的值。
env:Perl 获取运行环境中的信息,方法是存取%ENV哈希
例1:
#!/usr/bin/perl -w
%some_hash = ("foo",35,"bar",5,6,7);
@arra = %some_hash;
print "@arra \n";
例2:
#!/usr/bin/perl -w
chomp(@words=);
foreach $word (@words){
$count{$word} +=1;
}
foreach $word (keys %count){
print " $word was seen $count{$word} time.\n";
}
例3:
#!/usr/bin/perl -w
my %hash = ("a"=>1,"b"=>2,"c"=>3);
my @k = keys %hash;
my @v = values %hash;
my $count = keys %hash;
if (%hash){
print "That was a true value!\n";
}
#while (($keys,$values)= each %hash){
#print "$keys => $values\n"
#}
foreach $key (sort keys %hash){
$value = $hash{$key};
print "$key => $value \n";
}
$books{"fei"}=2;
$books{"fei1"}=3;
if ($books{$someone}){
print "$someone has at least one book checkout.\n";
}
if (exists $books{"fei"}){
print "Hey,there's a libary card for fei!\n";
}
阅读(921) | 评论(0) | 转发(0) |