activePerl 5.8基于
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
# declare a new hash
my %some_hash;
%some_hash = ("foo", 35, "bar", 12.4, 2.5, "hello",
"wilma", 1.72e30, "betty", "bye\n");
my @any_array;
@any_array = %some_hash;
print %some_hash;
print "\n";
print @any_array;
print "\n";
print $any_array[0];
print "\n";
print $any_array[1];
print "\n";
print $any_array[2];
print "\n";
print $any_array[3];
print "\n";
print $any_array[4];
print "\n";
print $any_array[5];
print "\n";
print $any_array[6];
print "\n";
print $any_array[7];
print "\n";
print $any_array[8];
print "\n";
print $any_array[9];
Run Code Online (Sandbox Code Playgroud)
输出为此
D:\learning\perl>test.pl
bettybye
bar12.4wilma1.72e+030foo352.5hello
bettybye
bar12.4wilma1.72e+030foo352.5hello
betty
bye
bar
12.4
wilma
1.72e+030
foo
35
2.5
hello
D:\learning\perl>
Run Code Online (Sandbox Code Playgroud)
是什么决定了我的示例代码中的元素打印顺序?
在Perl中打印混合(字符串,数字)哈希时要遵循的任何规则?谢谢.
bar12.4wilma1.72e+030foo352.5hello
Run Code Online (Sandbox Code Playgroud)
[更新]
在你们的帮助下,我更新了以下代码.
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
# declare a new hash
my %some_hash;
%some_hash = ("foo", 35, "bar", 12.4, 2.5, "hello",
"wilma", 1.72e30, "betty", "bye");
my @any_array;
@any_array = %some_hash;
print %some_hash;
print "\n";
print "\n";
print @any_array;
print "\n";
print "\n";
my @keys;
@keys = keys %some_hash;
for my $k (sort @keys)
{
print $k, $some_hash{$k};
}
Run Code Online (Sandbox Code Playgroud)
产量
D:\learning\perl>test.pl
bettybyebar12.4wilma1.72e+030foo352.5hello
bettybyebar12.4wilma1.72e+030foo352.5hello
2.5hellobar12.4bettybyefoo35wilma1.72e+030
D:\learning\perl>
Run Code Online (Sandbox Code Playgroud)
最终,在召唤keys和sort功能之后.哈希键打印遵循以下规则
2.5hellobar12.4bettybyefoo35wilma1.72e+030
Run Code Online (Sandbox Code Playgroud)
Eri*_*rom 22
哈希的元素以其内部顺序打印出来,这些元素不能被依赖,并且会随着元素的添加和删除而改变.如果您需要某种顺序的哈希的所有元素,请对键进行排序,并使用该列表来索引哈希.
如果您正在寻找按顺序保存其元素的结构,请使用数组,或者在CPAN上使用其中一个有序哈希.
您可以依赖列表上下文哈希扩展的唯一顺序是key =>值对将在一起.
散列的键以明显随机的顺序返回.实际的随机顺序在未来的Perl版本中可能会发生变化,但保证与值或每个函数产生的顺序相同(假设散列未被修改).从Perl 5.8.1开始,出于安全原因,即使在不同的Perl运行之间,排序也是不同的(参见perlsec中的算法复杂性攻击).
...
Perl从未保证散列键的任何排序,并且在Perl 5的生命周期中排序已经多次改变.此外,散列键的排序一直并且继续受插入顺序的影响.
还要注意,虽然哈希元素的顺序可能是随机的,但这个"伪目标"不应该用于随机混乱列表的应用程序(使用List :: Util :: shuffle(),参见List :: Util,a标准核心模块,自Perl 5.8.0;或CPAN模块Algorithm :: Numerical :: Shuffle),或用于生成排列(使用例如CPAN模块Algorithm :: Permute或Algorithm :: FastPermute),或用于任何加密应用程序.
注意:由于您在列表上下文中评估散列,因此至少保证每个键后跟其对应的值; 例如,你永远不会看到输出a 4 b 3 c 2 d 1.
| 归档时间: |
|
| 查看次数: |
14555 次 |
| 最近记录: |