What does “1;” mean in Perl?

前端 未结 7 792
梦如初夏
梦如初夏 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.

提交回复
热议问题