0
%group = ( 'forest', 'tree', 'crowd', 'person', 'fleet', 'ship' );

while ( ( $key, $value ) = each(%group) ) {
    print "A $value is part of a $key.\n";
}

This is the code and the output is this

A person is part of a crowd.
A tree is part of a forest.
A ship is part of a fleet.

why don't I get the output according to the order I have given in the array?

Miller
  • 34,962
  • 4
  • 39
  • 60
nadiyah123
  • 27
  • 11
  • 2
    That is not an array you specified. It us a hasmap and this has no order- – Jens Oct 06 '14 at 09:42
  • As Jens has pointed out, you are using a hash which has no notion of order. Check out [this thread](http://stackoverflow.com/questions/3638690/iterating-hash-based-on-the-insertion-order) for possible solution which uses `Tie::IxHash` module. – Andrei Oct 06 '14 at 09:44
  • i had this question in an exam and i had to write the output..how do i know that the output is given like that without it being A tree is part of a forest,A person is part of a crowd.,A ship is part of a fleet. – nadiyah123 Oct 06 '14 at 09:48

1 Answers1

2

You don't have an array, you have a hash. Hashes are unordered. If you want to impose order on your data, then use an array.

#!/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].";
}
Dave Cross
  • 68,119
  • 3
  • 51
  • 97