Perl哈希学习
来源:互联网 发布:心知天气是什么公司 编辑:程序博客网 时间:2024/06/10 06:21
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";
}
- Perl哈希学习
- Perl学习之哈希hash
- Perl: 关于学习Perl
- Perl学习笔记之数组与哈希
- 学习Perl
- Perl 学习
- perl学习
- Perl学习
- perl学习
- perl 学习
- PERL学习
- Perl学习
- 学习perl
- 学习perl
- perl学习
- Perl 哈希嵌套
- perl的哈希
- Perl-09---哈希变量
- 直角坐标系的平移和旋转
- 生活小窍门
- windows CE驱动开发学习笔记
- 毕业的冲动
- 多线程编程时的信号处理
- Perl哈希学习
- (转载)GNU的调试器gdb快速入门
- SQL查询慢的48个原因分析
- 动态链接库dll,静态链接库lib, 导入库lib
- 在图片控件中应用win32显示图片总结
- Cacti value: U和output: U问题两则
- CreateFile,ReadFile等API详解(或者说MSDN的翻译)
- Java的辉煌 还能延续多久?
- 2010-01-11