首页 技术 正文
技术 2022年11月16日
0 收藏 678 点赞 2,975 浏览 1677 个字

  今天做 Google的 Code Jam 上的一道题目:https://code.google.com/codejam/contest/351101/dashboard,用Perl语言解答的。遇到一个关于hash遍历的问题,思考了好一会儿才发现问题所在,为了简化叙述,写了一个简单的遍历哈希表的Perl程序如下:

  

  

   #!/usr/bin/perl
my %hash=(
=>"a",
=>"b",
=>"c",
=>"d",
=>"e",
=>"f",
=>"g",
=>"h",
=>"i",
=>"j",
);
for(keys %hash){
print "$_ => $hash{$_}\n";
}
my $times;
for(my $i=;$i<=;$i++){
$times=;
print "====================Loop No.$i:=====================\n";
LOOP1: while(my ($key,$value)=each %hash){
$times++;
print "\t'$key'=>'$value'\n";
if ($times>=){
last LOOP1;
}
}
}

该程序 2 ~ 13 行先建立了一个哈希表,然后遍历输出这个哈希表。

接下来的 18 ~ 28 行,用 while 循环和哈希表的 each 函数遍历该哈希表,用 for 循环控制遍历四次,每次遍历只遍历两个哈希表中的值。按照设想,这四次的遍历应当输出同样的内容,但输出如下:

 => f
=> c
=> g
=> i
=> b
=> h
=> a
=> d
=> j
=> e
====================Loop No.:=====================
'6'=>'f'
'3'=>'c'
====================Loop No.:=====================
'7'=>'g'
'9'=>'i'
====================Loop No.:=====================
'2'=>'b'
'8'=>'h'
====================Loop No.:=====================
'1'=>'a'
'4'=>'d'

由结果可以看出,这四次的输出并非都是一样的,这说明,用 while 循环 + each 函数遍历哈希表的时候,如果提前跳出了while循环,那么下次再接着用 each 函数遍历该哈希表的时候,会从上次已经遍历过的关键字的下一个关键字处开始遍历。

如果将 while 循环改成 for 或 foreach 循环呢?(Perl 中 for 和 foreach 其实是等价的):

   #!/usr/bin/perl
my %hash=(
=>"a",
=>"b",
=>"c",
=>"d",
=>"e",
=>"f",
=>"g",
=>"h",
=>"i",
=>"j",
);
for(keys %hash){
print "$_ => $hash{$_}\n";
}
my $times;
for(my $i=;$i<=;$i++){
$times=;
print "========== Loop No.$i ==========\n";
foreach(my ($key,$value)=each %hash){
$times++;
print "\t'$key'=>'$value' \tand times=$times\n";
}
}

输出结果如下:

 => f
=> c
=> g
=> i
=> b
=> h
=> a
=> d
=> j
=> e
========== Loop No. ==========
'6'=>'f' and times=
'6'=>'f' and times=
========== Loop No. ==========
'3'=>'c' and times=
'3'=>'c' and times=
========== Loop No. ==========
'7'=>'g' and times=
'7'=>'g' and times=
========== Loop No. ==========
'9'=>'i' and times=
'9'=>'i' and times=

每次 foreach 循环会遍历两次,而且并没有改变循环的关键字,有点奇怪啊…

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,955
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774