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?
$1 equals the text " brown ".
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"; }
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 $_.
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.
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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With