当我打印 Perl 哈希时,什么决定键的顺序? [英] What decides the order of keys when I print a Perl hash?

查看:32
本文介绍了当我打印 Perl 哈希时,什么决定键的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于activePerl 5.8

activePerl 5.8 based

#!C:Perlinperl.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 "
";
print @any_array;
print "
";
print $any_array[0];
print "
";
print $any_array[1];
print "
";
print $any_array[2];
print "
";
print $any_array[3];
print "
";
print $any_array[4];
print "
";
print $any_array[5];
print "
";
print $any_array[6];
print "
";
print $any_array[7];
print "
";
print $any_array[8];
print "
";
print $any_array[9];

输出为这个

D:learningperl>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:learningperl>

是什么决定了我的示例代码中的元素打印顺序?

What decided the elements print order in my sample code?

在 Perl 中打印混合(字符串、数字)哈希时要遵循什么规则?谢谢.

Any rule to follow when print a mixed(strings, numbers) hash in Perl? Thank you.

bar12.4wilma1.72e+030foo352.5hello

[更新]

在你们的帮助下,我更新了代码如下.

With you guys help, i updated the code as below.

#!C:Perlinperl.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 "
";
print "
";
print @any_array;
print "
";
print "
";

my @keys;
@keys = keys %some_hash;
for my $k (sort @keys)
{
    print $k, $some_hash{$k};
}

输出

D:learningperl>test.pl
bettybyebar12.4wilma1.72e+030foo352.5hello

bettybyebar12.4wilma1.72e+030foo352.5hello

2.5hellobar12.4bettybyefoo35wilma1.72e+030
D:learningperl>

最后,在调用了keyssort 函数之后.哈希键打印遵循以下规则

Finially, after called keys and sort functions. The hash keys print followed the rule below

2.5hellobar12.4bettybyefoo35wilma1.72e+030

推荐答案

散列的元素按其内部顺序打印出来,不能依赖,并且会随着元素的添加和删除而改变.如果您需要以某种顺序排列散列的所有元素,请对键进行排序,然后使用该列表来索引散列.

Elements of a hash are printed out in their internal order, which can not be relied upon and will change as elements are added and removed. If you need all of the elements of a hash in some sort of order, sort the keys, and use that list to index the hash.

如果您正在寻找一种按顺序保存其元素的结构,请使用数组,或使用 CPAN 上的有序散列之一.

If you are looking for a structure that holds its elements in order, either use an array, or use one of the ordered hash's on CPAN.

从列表上下文散列扩展中唯一可以依赖的顺序是键 => 值对将在一起.

the only ordering you can rely upon from a list context hash expansion is that key => value pairs will be together.

这篇关于当我打印 Perl 哈希时,什么决定键的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆