Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "1;" mean in Perl?

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  => ( $] >= 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; 

What is the significance of 1; and of the curly braces that enclose the $somevar and the Sub?

like image 584
Anand Shah Avatar asked Dec 21 '09 13:12

Anand Shah


People also ask

What is $1 Perl?

$1 equals the text " brown ".

What is $_ in Perl?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

What does =~ in Perl?

9.3. The Binding Operator, =~ Matching against $_ is merely the default; the binding operator (=~) tells Perl to match the pattern on the right against the string on the left, instead of matching against $_.

How do I check if a line is empty in Perl?

You can do something like shown below, inside the loop: if ($_ =~/^$/) { ... } Show activity on this post. It will open the file specified as arg0 on command line and print every line except the empty.


2 Answers

1 at the end of a module means that the module returns true to use/require statements. It can be used to tell if module initialization is successful. Otherwise, use/require will fail.

$somevar is a variable which is accessable only inside the block. It is used to simulate "static" variables. Starting from Perl 5.10 you can use keyword state keyword to have the same results:

## Starting from Perl 5.10 you can specify "static" variables directly. sub Somesub {     state $somevar; } 
like image 119
Ivan Nevostruev Avatar answered Oct 08 '22 14:10

Ivan Nevostruev


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.

like image 39
tsee Avatar answered Oct 08 '22 16:10

tsee