Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sort function in Perl – random output

I’m trying to write a sort function in Perl. I need that "name_iwant_last" will be the last in sorted hash.

My code:

%libs = (
"00000000000","00000000000",
"aaaaaaaaaaa","aaaaaaaaaaa",
"AAAAAAAAAA","AAAAAAAAAA",
"name_iwant_last","name_iwant_last",
"zzzzzzzzzzzzz","zzzzzzzzzzzzz",
"ZZZZZZZZZZZ","ZZZZZZZZZZZ",
"9999999999","9999999999"
);

sub lib_sort {
  #print "cosa ordino ";
  #print $libs{$a};
  #print $libs{$b};
  #print "\n";
  return 1 if (index($libs{$a} , "name_iwant_last") != -1);
 return -1 if $libs{$a} < $libs{$b};
  return 0 if $libs{$a} == $libs{$b};
  return 1 if $libs{$a} > $libs{$b};
}

foreach my $lib (sort lib_sort values %libs) {
    print $lib;
    print "\n";
}

But when i run this code… the print are in random order…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected:
aaaaa
AAAAA…
name_iwant_last

resulted:
random!!!

>Solution :

If you add use warnings to your code, then you’ll see a few warnings like this:

Argument "ZZZZZZZZZZZ" isn’t numeric in numeric lt (<) at sort line 20.
Argument "AAAAAAAAAA" isn’t numeric in numeric lt (<) at sort line 20.
Argument "zzzzzzzzzzzzz" isn’t numeric in numeric lt (<) at sort line 20.
Argument "aaaaaaaaaaa" isn’t numeric in numeric lt (<) at sort line 20.
Argument "name_iwant_last" isn’t numeric in numeric lt (<) at sort line 20.

You’re comparing strings, but you’re using the numeric comparison operators (<, ==, >). If you switch to using string comparison operators (lt, eq, gt) then it will work as expected.

And always have use warnings and use strict in your code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading