tc1364 has asked for the wisdom of the Perl Monks concerning the following question:

Can you please show me what is wrong with the below syntax because the code doesn't sort in the sub routine? Everthing else appears to works OK.
sub xls () { my ($hashref) = @_; my @keys = sort { $a cmp $b } (keys %{$hashref}); for my $key (keys %{$hashref}) { my $val = $hashref->{$key}; my ($a, $b, $c, $d, $e) = split(/\s+/, $val, 5); $worksheet->write($y, 0, $a, $field_data); $worksheet->write($y, 1, $key, $field_data); $worksheet->write($y, 2, $b, $field_data); $worksheet->write($y, 3, $c, $field_data); $worksheet->write($y, 4, $d, $field_data); $worksheet->write($y, 5, $e, $field_data); $y++; } $y++; }

Retitled by davido from "Syntax error", per consideration to improve searchability.

Replies are listed 'Best First'.
Re: Syntax error sorting hash keys
by Velaki (Chaplain) on Dec 13, 2004 at 17:23 UTC

    Ummm, in your code, you loop over a list of keys returned by the keys function. This function doesn't guarantee any specific order of retrieval.

    You sorted a list of the keys before the loop, but you didn't use that list in the for loop. Perhaps you meant something like:

    for my $key (@keys) {
    ?

    Hope that helped,
    -v
    "Perl. There is no substitute."
      Yes.. you are right. Thank you!
Re: Syntax error sorting hash keys
by si_lence (Deacon) on Dec 13, 2004 at 17:40 UTC
    Hi,
    You are useing a prototype for your function that accepts
    no arguments: sub xls () {}
    So you cannot pass any arguments to this function.
    If you drop the parenthesis it should work (at least from a syntactic
    point of view). To get the sorted output see the answer by Velaki
    si_lence
      So you cannot pass any arguments to this function.

      Only if the function is declared before the use. If the function is used before it is declared, the prototype will not have a chance to be enforced. Of course, if the OP was using warnings, he would get a "sub called too early to check prototype" message in this case.

      Update: just to make it clear, I am not endorsing the use of empty prototypes, just further explaining the behavior.

Re: Syntax error sorting hash keys
by ysth (Canon) on Dec 13, 2004 at 20:26 UTC
    By the way, $a cmp $b is the default sort comparison, so you could have said just my @keys = sort keys %$hashref; or even bypassed using a @keys array by saying
    for my $key (sort keys %$hashref) {
    But including $a cmp $b doesn't slow anything down, since any of $a cmp $b, $b cmp $a, $a <=> $b, or $b <=> $a is optimized away and handled internally by the sort operation. Any other comparison block gets executed as real perl code, so is quite a bit slower.