Perl ($_, @_) 中下划线的意义是什么? [英] What is the significance of an underscore in Perl ($_, @_)?

查看:132
本文介绍了Perl ($_, @_) 中下划线的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Perl 的新手,我是这样使用它们的

I am new to Perl, and I used them like this

$_

foreach (@list) {
    print "$_\n";
}

@_

sub search {
    my ($no, @list) = @_;
}

这些下划线变量在 Perl 中究竟是如何工作的?它们还有哪些有用的结构?

How exactly do these underscore variables work in Perl? What are the other constructs where they are useful?

推荐答案

这种问题表明你真的应该阅读一本书,也许还有 Perl 标签的其余部分 常见问题解答.

This is the sort of question which indicates you really should be reading a book, and perhaps the rest of the Perl tag FAQs.

尽管如此,$_ 是一个上下文变量,它由某些构造隐式创建并由某些内置函数隐式使用.以下是一些示例:

Nevertheless, $_ is a context variable which is created implicitly by certain constructs and used implicitly by certain built-in functions. Here are some examples:

while(<>) {
    next if /^#/;
    last if /^q(?:uit)?$/;
    say "Howdy!" if /^hello$/;
}

这做了很多设置和检查 $_ 变量,相当于:

This doing a lot of work setting and inspecting the $_ variable and is equivalent to:

while(defined($_ = <>)) {
    next if $_ =~ /^#/;
    last if $_ =~ /^q(?:uit)?$/;
    say "Howdy!" if $_ =~ /^hello$/;
}

设置 $_ 的其他结构是:foreach 循环、given 块、mapgrep 操作和 Try:: 中的 catch 块小.

Other constructs which set $_ are: foreach loops, given blocks, map and grep operations, and catch blocks in Try::Tiny.

其他使用 $_ 的结构是:裸 print; 语句、s/// 替换运算符和 tr/// 音译运算符.

Other constructs which use $_ are: bare print; statements, the s/// substitution operator and the tr/// transliteration operator.

我的建议是:在您学习 Perl 时,不要暗中使用 $_.完整地写下来(如上面的第二个例子),以在你的脑海中强化实际发生的事情.就像你学习外语一样,在你学会简写语言之前,你应该学会正确和仔细地说话.

I'd advise this: while you are learning Perl, don't use $_ implicitly. Write it all out in full (as in the second example above), to reinforce in your mind what is actually going on. Just like when you are learning a foreign language, you should learn to speak properly and carefully before you learn to abbrv y'language.

$_ 对于编写更短、更简洁的代码很有用,并且通过专注于正在进行的处理而不是正在执行的变量实际上可以更清晰,但前提是您已经学会了哪些操作使用 $_ 的第二个性质.否则就是一团糟.

$_ is useful for writing shorter, terser code, and can actually be clearer by focussing on the processing going on rather than the variables it is being done to, but only once you have learned as second nature which operations are using $_. Otherwise it's just a confusing mess.

如别处所述,@_ 是子程序的参数列表.

As mentioned elsewhere, @_ is the argument list to a subroutine.

这篇关于Perl ($_, @_) 中下划线的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆