0
%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.

为什么我没有按照我在数组中给出的顺序得到输出?

4

1 回答 1

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].";
}
于 2014-10-06T09:50:56.193 回答