Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

sorting - What exactly are "$a" and "$b" in Perl's "sort()" function?

I understand how to get the results I want from using Perl's sort() function, this is more a question about the inner workings of sort().

Where do the "$a" and "$b" variables come from? I read through the documentation for sort and it seems unclear. What are "$a" and "$b" and what makes them special?

ex:

my @sorted_list = sort {$a cmp $b} @unsorted_list;

How does sort know what to do with "$a" and "$b" and why don't you get the "Global symbol requires explicit package name" error for "$a" or "$b"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$a and $b are exempt global variables; they are exempt in that Perl allows them to be used (anywhere) without being declared. They are set by the sort function. Use of any other undeclared global in sort (in strict mode) will trigger an error.

The sort function accepts various forms of input, one being a code block, which is the form you are referring to.

{$a cmp $b} is a code block, it is parsed and passed as a "chunk of code" to the sort function, and Perl checks the arguments for sort and if it receives a code block, sort will set $a and $b, if they exist as package globals within the code block, and assign each pair of items being sorted to $a and $b. All you have to do is refer to them to control the sort algorithm. Otherwise, the internal algorithm is used (which I think is merge sort).

http://perldoc.perl.org/functions/sort.html

$a and $b are not lexicals, they are package globals (or just globals).

In a main you can write:

sort {$main::a cmp $main::b} @list;

Or in another package, you could write:

package foo;

sort {$foo::a cmp $foo::b} @list;

You shouldn't actually prefix like this; I am demonstrating that $a and $b are actually globals within your current package, and not some magic $a within the sort function, although Perl knows to allow you to define them even with strict mode.

You can't just use any variables (in strict mode). Try:

sort {$A cmp $B} @list;

Global symbol "$A" requires explicit package name at sort.pl

You cannot use a lexical (my $a) in scope of sort.

my $a;
sort {$a cmp $b} @list;

Can't use "my $a" in sort comparison at sort.pl line 13.

$a and $b are special anywhere in Perl. They are exempt from strict mode, which is unrelated to sort, though sort was the reason for the exemption.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...