gpt4 book ai didi

Perl 语法标志

转载 作者:行者123 更新时间:2023-12-04 04:48:32 25 4
gpt4 key购买 nike

请问&有什么用在没有它的潜艇面前,潜艇仍然能够运行。

而且,my在 perl 变量前面。

我知道这是为了严格的语言语法或其他什么,但他们为什么不把它作为一个标准,每个变量都需要由 my 声明?

编辑

感谢您的所有讨论/回答,我希望接受您的许多回答,但由于我只能接受一个,我将接受其他用户可能轻松理解的一个。

最佳答案

在 Perl 中,函数调用已被优化为不需要 &无时无刻不在。当你声明一个子程序时:

sub hello {print "world\n"}

您可以将其称为 hello;hello();&hello();这都会做同样的事情。

如果您的子例程接受参数,则有点不同:
sub hello {print "Hello, @_!\n"}

hello 'World'; # prints 'Hello, World!'
hello('World'); # same
&hello('World'); # same

hello; # prints 'Hello, !'
&hello(); # same
&hello; # different, uses whatever was in @_ when hello was called

@_ = 'Bob';

hello; # prints 'Hello, !'
&hello(); # prints 'Hello, !'
&hello; # prints 'Hello, Bob!'

如您所见,使用 & sigil 在很大程度上是多余的,除非在没有参数列表的情况下。在这种情况下,使用 @_ 中的当前值调用子例程。 .
& sigil 还有另一个特殊行为,与 Perl 的原型(prototype)有关。假设您正在编写自己的 keys函数,并希望它表现得像 Perl 的:
sub mykeys (\%) {keys %{$_[0]}}

这里 (\%)原型(prototype)告诉 perl mykeys 的第一个参数必须是文字哈希(将作为哈希引用传入)。
my $hashref = {...};

say for mykeys %$hashref;

如果由于某种原因你需要绕过这个要求(通常不是最好的主意),你可以这样写:
say for &mykeys( $hashref );  # note that there is no `%`

在这种情况下,添加 &在 sub 禁用原型(prototype)检查和它会执行的任何后续操作之前(例如获取引用)。在这种用法中, &基本上是一个断言,您确切知道哪些参数 mykeys需要,并且您不希望 perl 妨碍您。

一般来说,使用 &应该避免 on 子程序,除非您明确想要我上面提到的行为之一。

最后, &当您引用实际的代码引用时,也需要:
my $coderef = \&hello;

或者
if (defined &hello) {print "hello is defined\n"}  # but is not called

正如其他人所提到的, my运算符在当前词法范围内声明变量。 use strict; 时需要编译指示已加载。 Perl 有两种类型的变量,用 my 声明的词法变量。 , 和包变量。
my变量存在于所谓的 lexical pad 中,它是 Perl 每次引入新作用域时创建的存储空间。包变量存在于全局符号表中。
use strict;
use warnings;

$main::foo = 5; # package variable

{ # scope start
my $foo = 6;

print "$foo, $main::foo\n"; # prints '6, 5';
} # scope end

print "$foo, $main::foo\n"; # syntax error, variable $foo is not declared

您可以使用 our为全局变量创建词法别名的关键字:
use strict;


our $foo = 5; # $main::foo == $foo


{ # scope start
my $foo = 6;

print "$foo, $main::foo\n"; # prints '6, 5';
} # scope end

print "$foo, $main::foo\n"; # prints '5, 5'
# since $foo and $main::foo are the same

关于Perl 语法标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5027415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com