Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, do "$a" and "$b" have any special use outside of the sort() function?

I asked a question about the use of "$a" and "$b" in Perl's sort() function the other day:

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

I now have a follow up question. Are "$a" and "$b" only used by sort() or is there any other Perl function that takes advantage of these special global variables?

Or even if no other function uses them, are there any situations outside of sort() that you would use "$a" or "$b"?

Edit:

To clarify:

In short, the question is can "$a" and "$b" be used by something other than sort()?

I am just curious to see what other situations they can be used in. I have never seen "$a" or "$b" used by anything else and was wondering have any other special use outside of sort().

like image 673
tjwrona1992 Avatar asked Sep 02 '25 01:09

tjwrona1992


1 Answers

can "$a" and "$b" be used by something other than sort()?

As it has already been explained, there's nothing special about $a and $b (except that they are predeclared). Asking if an ordinary variable can be used by some thing other than one function makes no sense. Here is $a being used by something that isn't sort:

 $ perl -E'$a=123; say $a;'
 123

That said, it's not a very good idea to do so. It's best to use lexical variables, and declaring $a or $b as lexical variables will render them unavailable to use in sort (or in List::Util's functions) without an overriding our ($a,$b);.

$ perl -e'sub foo { my ($a) = @_; "..."; sort { $a cmp $b } @a; "..." }'
Can't use "my $a" in sort comparison at -e line 1.
like image 106
ikegami Avatar answered Sep 07 '25 12:09

ikegami