简体   繁体   中英

Perl subroutine sort my_compare (@d);

I am taking an online perl class and we started subroutines. The professor used this example:

@d = (1, 5, 2, 9, 8, 7, 10, 11);

@c = sort my_compare (@d);

# Print the result
print "Before sort:\t".join(", ", @d) . "\n";
print "After sort:\t".join(", ", @c) . "\n";    

sub my_compare
{
    if ($a < $b) { return -1; }
    elsif ($a > $b) { return 1; }
    else  { return 0; }
}

I dont understand the @c = sort my_compare (@d); statement and why I cannot rename the variables $a and $b . This is completely different than what I am used to doing for soubroutines in languages like C and C++.

Could somebody explain this to me?

Thank you for your help! Zahra

Unlike many other languages, Perl is like slang. Less consistent, but full of very useful shortcuts. As Larry Wall stated:

In general, they (Perl operators) do what you want, unless you want consistency.

For the C library qsort function, you always need to provide a function pointer called compar , that will do the actual comparison of value pairs.

void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));

This is very similar in Perl, but providing comparison code is optional. This uses the default built-in alphabetic comparison.

sort @d

The whole reason of the above exercise is to replace the alphabetic comparison with a numeric one. You can provide custom comparison code in the form of a subroutine name or a block.

sort subname @d;
sort { $a <=> $b } @d;

The above is the most simple solution to your problem, using the numeric comparison operator <=> . It does the same as sub my_compare .

And well, $a and $b are just built in. Perl has no function prototypes with parameter names, so they had to name it somehow.

See http://perldoc.perl.org/functions/sort.html for further details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM