什么是"1;" Perl意味着什么?

Ana*_*hah 33 perl perl-module

我遇到了一些Perl模块,例如类似于以下代码:

package MyPackage;

use strict;
use warnings;
use constant PERL510  => ( $] >= 5.0100 );

require Exporter;

our @ISA = qw(Exporter);  
our @EXPORT = qw( );

{  #What is the significance of this curly brace?

    my $somevar;

    sub Somesub {
      #Some code here 
    }
}

1;
Run Code Online (Sandbox Code Playgroud)

1;包围$somevar和Sub 的花括号的意义是什么?

Iva*_*uev 67

1在模块的端部是指,该模块返回trueuse/require语句.它可用于判断模块初始化是否成功.否则,use/require将失败.

$somevar是一个只能在块内访问的变量.它用于模拟"静态"变量.从Perl 5.10开始,您可以使用关键字state关键字来获得相同的结果:

## Starting from Perl 5.10 you can specify "static" variables directly.
sub Somesub {
    state $somevar;
}
Run Code Online (Sandbox Code Playgroud)

  • Upvote,因为这个答案既简洁又正确,实际上回答了所有父母的问题. (6认同)

tse*_*see 11

使用use Fooor 加载模块"Foo"时require(),perl Foo.pm像普通脚本一样执行文件.如果模块正确加载,它希望它返回一个真值.这样1;做.这可能是2;或者"hey there";一样好.

声明$somevar和函数周围的块Somesub限制了变量的范围.这样,它只能从Somesub每次调用中访问并且不会被清除Somesub(如果在函数体内声明它就是这种情况).这个习惯用法已被最近版本的perl(5.10及更高版本)取代,后者有state关键字.


Que*_*tin 8

模块必须返回真值.1是真正的价值.


Ed *_*ess 8

Perl模块必须返回评估为true的内容.如果他们不这样做,Perl报告错误.

C:\temp>cat MyTest.pm
package MyTest;
use strict;
sub test { print "test\n"; }
#1;  # commented out to show error

C:\temp>perl -e "use MyTest"
MyTest.pm did not return a true value at -e line 1.
BEGIN failed--compilation aborted at -e line 1.

C:\temp>
Run Code Online (Sandbox Code Playgroud)

虽然习惯使用"1;",但任何评估为true的东西都会起作用.

C:\temp>cat MyTest.pm
package MyTest;
use strict;
sub test { print "test\n"; }
"false";

C:\temp>perl -e "use MyTest"

C:\temp>  (no error here)
Run Code Online (Sandbox Code Playgroud)

对于显而易见的原因,另一种流行的返回值是42.

http://returnvalues.useperl.at/values.html上有一个很酷的返回值列表.