What exactly are “$a” and “$b” in Perl's “sort()” function?

前端 未结 3 1233
情深已故
情深已故 2020-12-06 01:49

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().

3条回答
  •  暖寄归人
    2020-12-06 02:36

    What exactly are “$a” and “$b” in [the compare code of] Perl's “sort()” function?

    Two values from the list of values to sort. The block is to return information as to how one should be positioned to the other in the final result.

    What are "$a" and "$b" and what makes them special?

    Package variables, and there's nothing special about them except that use strict 'vars'; does not consider using them to be an error.

    Where do the "$a" and "$b" variables come from?

    They are populated by sort.

    How does sort know what to do with "$a" and "$b"

    It doesn't do anything with them except populate them as required to perform its function.

    why don't you get the "Global symbol requires explicit package name" error for "$a" or "$b"?

    That would make it rather hard to use them!

    What happens if you define a local variable, my $a or my $b, and then try and use sort within a scope where those [lexical] variables are visible?

    If your compare function is in scope of a my $a and/or my $b, it will use those variables instead of the package variables sort populates.

    Perl realizes you might be an easy mistake to make, so it checks for it.

    $ perl -c -e'sort { my ($a,$b); $a cmp $b } @a;'
    Can't use "my $a" in sort comparison at -e line 1.
    

提交回复
热议问题