Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Curious code question 2

Status
Not open for further replies.

KevinADC

Technical User
Jan 21, 2005
5,070
US
The code:

Code:
sub sort_by_num  { 
   return $a <=> $b; 
} 
 
@arr = (500,1,400,5); 
 
foreach (sort sort_by_num(@arr)) { 
   print ("$_\n"); 
}

the output:

1
5
400
500

My question is why is that weird code producing that weird output? This is not real code, I am just asking out of curiousity sake since I was not able to explain it myself.

sort_by_num appears to be doing nothing but it does have an affect on the sort function since the output should be:

1
400
5
500

using just a straight sort:

@arr = sort (@arr);
 
Adding in a couple of print statements to the sort_by_num subroutine shows that $a and $b are being set, and you're getting a numeric sort.

It seems to me that despite the way the parentheses are written, perl's using the "sort SUBNAME LIST" syntax for the sort function. It behaves the same way with:
Code:
foreach ( sort sort_by_num @arr ) {
   print "$_\n";
}
. . . except in that case it's what you'd expect to happen. Seems a bit counterintuitive to me. I'd have expected (as you are, I think) that the elements of @arr would be passed to the sort_by_num subroutine as normal, and that sub's output would then be sorted using the standard asciibetical sort.
 
perl's using the "sort SUBNAME LIST" syntax for the sort function.

That is the explanation. I realized that last night after some reading on the sort function and how it handles a named SUB for the sort instead of an anonymous sub. Perl passes the arguments to the named SUB in the package globals $a and $b just like it would in the anonymous sub instead of using the system array. The perl compiler seems to be smart enough to ignore the parenthesis when using a named SUB and treats the line just like you posted:

Code:
foreach ( sort sort_by_num @arr )

thanks, have a star ish. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top