为什么 Perl 的这一行本身只包含一个变量?

发布于 2024-09-30 12:06:20 字数 208 浏览 8 评论 0原文

我越深入越喜欢 Perl,但我对在我正在查看的模块的子例程中看到的一行有疑问。

my $var = 1;
....
....
....
....
$var;

让我感到困惑的是看到 $var 独自在一行上。这只是返回 1 的迂回方式吗?

非常感谢!

I like perl the more I am getting into it but I had a question about a line I saw in a subroutine in a module I am looking through.

my $var = 1;
....
....
....
....
$var;

What throws me is just seeing that $var all by itself on a line. Is that just a roundabout way of returning 1 ?

Many thanks!

Jane

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦初启 2024-10-07 12:06:20

在 perl 中,块的值是块中最后一个表达式的值。这只是 return $var 的简写。

编辑:纯粹主义者指出,块一般不会返回值(例如,像 Scala 中那样),因此您不能编写:

my $x = if (cond) { 7 } else { 8 };  # wrong!

子例程、eval 或 do FILE 的隐式返回值是最后计算的表达式。不过,最后一个表达式可以位于块内:

sub f {
    my $cond = shift;
    if ($cond) { 7 } else { 8 }  # successfully returns 7 or 8 from f()
}

if/else 块表面上看起来返回一个值,尽管严格来说,它们并不返回值。

In perl the value of a block is the value of the last expression in the block. That is just a shorthand for return $var.

EDIT: Purists point out that that blocks in general do not return values (like they do in Scala, for example) so you can't write:

my $x = if (cond) { 7 } else { 8 };  # wrong!

The implicit return value of a subroutine, eval or do FILE is the last expression evaluated. That last expression can be inside a block, though:

sub f {
    my $cond = shift;
    if ($cond) { 7 } else { 8 }  # successfully returns 7 or 8 from f()
}

There is the superficial appearance of the if/else blocks returning a value, even though, strictly speaking, they don't.

我一向站在原地 2024-10-07 12:06:20

引用 perldoc -f return 的最后一行:

在没有显式返回的情况下,子例程、eval 或 do FILE 会自动返回最后计算的表达式的值。

Quoting the last line of perldoc -f return:

In the absence of an explicit return, a subroutine, eval, or do FILE automatically returns the value of the last expression evaluated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文