What does “1;” mean in Perl?

前端 未结 7 777
梦如初夏
梦如初夏 2020-12-24 11:36

I have come across a few Perl modules that for example look similar to the following code:

package MyPackage;

use strict;
use warnings;
use constant PERL510         


        
相关标签:
7条回答
  • 2020-12-24 12:11

    Perl modules must return something that evaluates to true. If they don't, Perl reports an error.

    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>
    

    Although it's customary to use "1;", anything that evaluates to true will work.

    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)
    

    For obvious reasons another popular return value is 42.

    There's a list of cool return values maintained at http://returnvalues.useperl.at/values.html.

    0 讨论(0)
  • 2020-12-24 12:13

    I don't know much about Perl, but usually you create a scope using curly braces. Probably $somevar shoudln't be available globally?

    0 讨论(0)
  • 2020-12-24 12:26

    Modules have to return a true value. 1 is a true value.

    0 讨论(0)
  • 2020-12-24 12:26

    From the documentation for require:

    The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1; , in case you add more statements.

    0 讨论(0)
  • 2020-12-24 12:28

    When you load a module "Foo" with use Foo or require(), perl executes the Foo.pm file like an ordinary script. It expects it to return a true value if the module was loaded correctly. The 1; does that. It could be 2; or "hey there"; just as well.

    The block around the declaration of $somevar and the function Somesub limits the scope of the variable. That way, it is only accessible from Somesub and doesn't get cleared on each invocation of Somesub (which would be the case if it was declared inside the function body). This idiom has been superseded in recent versions of perl (5.10 and up) which have the state keyword.

    0 讨论(0)
  • 2020-12-24 12:30

    The curly braces limit the scope of the local variable $somevar:

    { my $somevar; ... } # $somevar's scope ends here

    0 讨论(0)
提交回复
热议问题