在Perl中,执行"$ a"和"$ b"在sort()函数之外有什么特殊用途? [英] In Perl, do "$a" and "$b" have any special use outside of the sort() function?
问题描述
前几天我问了有关在Perl的sort()
函数中使用"$ a"和"$ b"的问题:
I asked a question about the use of "$a" and "$b" in Perl's sort()
function the other day:
"$ a"到底是什么?和"$ b"在Perl的"sort()"中功能?
我现在有一个后续问题.是sort()
仅使用"$ a"和"$ b",还是有其他Perl函数利用这些特殊的全局变量?
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?
或者即使没有其他函数使用它们,在sort()
之外是否还有其他情况需要使用"$ a"或"$ b"?
Or even if no other function uses them, are there any situations outside of sort()
that you would use "$a" or "$b"?
要澄清:
简而言之,问题是sort()
之外的其他东西可以使用"$ a"和"$ b"吗?
In short, the question is can "$a" and "$b" be used by something other than sort()
?
我只是想知道它们还能在什么其他情况下使用.我从未见过"$ a"或"$ b"被其他任何东西使用,并且想知道在sort()
之外还有其他特殊用途./p>
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()
.
推荐答案
sort()
以外的其他东西可以使用"$ a"和"$ b"吗?
can "$a" and "$b" be used by something other than
sort()
?
正如已经解释过的,$a
和$b
没有什么特别的(除了它们是预先声明的).询问一个普通变量是否可以被一个函数以外的其他东西使用是没有道理的.这是$a
被不是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
也就是说,这样做不是一个好主意.最好使用词法变量,并将$a
或$b
声明为词法变量将使其无法使用. sort
(或在List :: Util的函数中)而没有优先级our ($a,$b);
.
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.
这篇关于在Perl中,执行"$ a"和"$ b"在sort()函数之外有什么特殊用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!