In my perl progarm i have the following code:
@alpha=('toM','jERRy','mickeY','MARio');
print sort{$a cmp $b} @alpha,' "***MIDDLE STRING***" ';
here it prints the
‘ “***MIDDLE STRING***” ‘
first and then the sorted @alpha list. Why it prints in reverse order, when
print "a","b";
prints
ab
in correct order. I googled for help but it speaks about “reverse” function/method of perl but i don’t use that function in my code. I found the answers irrelevant.
I guess it deals something with internal working of “print” function, using “stack” data structure, but I have no idea. Somebody help me out.
Thanks in advance…
#1 and #2 are equivalent:
sortis operating on a list containing all of the elements of@alphaplus the string, thanks to Perl’s automatic flattening of lists. You might be tempted to add some parentheses aroundsort(#3), but that doesn’t help you either, because it’s interpreted as a list of two elements (#4): the result of callingprint, and the string. Thus the string will not be printed, because it has nothing to do withprint.You could use an extra set of parentheses (#5) or split it up (#6), but knowing
sort {$a cmp $b} @alphais identical tosort @alpha, you can omit the block and the parentheses become straightforward (#7). And by the same rule, if you do need a comparison function, you can put both arguments tosortwithin parentheses, not separated by a comma (#8).I also like to define subs for different kinds of sorting, to make the code simpler to read: