-2

I knew this is a very basic question in Perl so i could not find solution for this anywhere.

I am using Perl package Text::ASCIITable to beautify the output.

Below is my code, where i am constructing table row using array.

my @output =  [
    {
        one => "1",
        two => "2",
        three => "3",
        four => "4",        
    },
    {
        one => "1",
        two => "2",
        three => "3",
        four => "4",    
    }
];  

my $t = Text::ASCIITable->new();

# Table header values as static. 
$t->setCols('one','two','three','four');

foreach my $val ( @output ) {
    my @v = values $val;
    push @$t, @v;
}

print $t;

This gives me output as below

.-----+-----+-------+------.
| one | two | three | four |
|=----+-----+-------+-----=|
| 1   | 2   | 3     | 4    |  
| 2   | 4   | 3     | 1    |  
'-----+-----+-------+------'

The problem is, the table row is getting shuffled and it does not match with table header. Because the given input array sort itself that makes me annoying.

So how to stop Perl to sort array? I just want get the result as it is.

Any help would be appreciated greatly.

Raja
  • 3,477
  • 12
  • 47
  • 89
  • 1
    Your "code" contains syntax errors. "*Verifiable – Test the code you're about to provide to make sure it reproduces the problem.*" – melpomene Sep 07 '16 at 19:28
  • 1
    The code `my @v = values $val;` (when corrected to `my @v = values %$val;`) returns the values in *random* order. That's how hashes work. Also, you don't use `@v` at all but push `@output` instead. – PerlDuck Sep 07 '16 at 19:35
  • 1
    @PerlDog Except `@output` only has a single element and `$val` is an array reference. Or it would be if the data was in valid Perl syntax. – melpomene Sep 07 '16 at 19:38
  • 1
    `one: "1"` is not valid Perl. That looks like broken JSON if anything. – stevieb Sep 07 '16 at 19:58
  • Note: `values $val` is *experimental*. You should be using `values %$val`. – ikegami Sep 07 '16 at 20:32
  • @PerlDog: It's probably better to think of it as *arbitary* order rather than random. `perldoc -f values` does say "Hash entries are returned in an apparently random order.", but you shouldn't depend on that; for example, depending on `values %whatever` to be in a truly random order is a bad idea. (As I recall, in old versions of Perl the order was decidedly non-random -- but still arbitrary.) – Keith Thompson Sep 07 '16 at 21:06

1 Answers1

2

It's not being sorted. Quite the opposite, the problem is that you didn't order the values. Fixed:

my @field_names = qw( one two three four );

$t->setCols(@field_names);

for my $val ( @output ) {
   push @$t, @$val{@field_names};
}
ikegami
  • 367,544
  • 15
  • 269
  • 518