Yadheendran Yadheendran - 2 months ago 7
Perl Question

How to stop array sort in Perl

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.

Answer

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};
}