%group = ( 'forest', 'tree', 'crowd', 'person', 'fleet', 'ship' );
while ( ( $key, $value ) = each(%group) ) {
print "A $value is part of a $key.\n";
}
这是代码,输出就是这个
A person is part of a crowd.
A tree is part of a forest.
A ship is part of a fleet.
为什么我不按照我在阵列中给出的顺序获得输出?
答案 0 :(得分:2)
你没有数组,你有一个哈希。哈希是无序的。如果要对数据强制执行订单,请使用数组。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
my @groups = (
[ 'forest','tree' ],
[ 'crowd','person' ],
[ 'fleet','ship' ],
);
foreach my $group (@groups) {
say "A $group->[1] is part of a $group->[0].";
}