Lokesh R Gowda
Lokesh R Gowda

Reputation: 15

how to access variables from .pm file to an .pl file

1.pm

package 1;
our $Var= "hello";

2.pl

use 1;
print "$Var\n";

am doing exactly what I am mentioned above in 2 files 1.pm and 2.pl. in 2.pl I am not able to access that variable $Var.

Please can you help me out? How should I declare that variable in the 1.pm file (the variable should be global)?

Thanks,

Upvotes: 0

Views: 2195

Answers (2)

Matteo
Matteo

Reputation: 14940

Summary: package names cannot begin with a number

Detailed description:

First of all always use

use strict;
use warnings;

in your scripts. You would have noticed an error message:

Global symbol "$Var" requires explicit package name at 2.pl line 6.
Execution of 2.pl aborted due to compilation errors.

You can access it using the package name

$1::Var

but you will get

Bareword found where operator expected at 2.pl line 6, near "$1::Var"
    (Missing operator before ::Var?)
Bareword "::Var" not allowed while "strict subs" in use at 2.pl line 6.
Execution of 2.pl aborted due to compilation errors.

Try using a module name not beginning with a number. E.g., Mod.pm

package Mod;

use strict;
use warnings;

our $Var= 'hello';
1;

and 2.pl

use warnings;
use strict;

use Mod;

print $Mod::Var . "\n";

1;

From perlmod

Only identifiers starting with letters (or underscore) are stored in a package's symbol table.

Although not mandatory it is customary (and strongly suggested) to capitalize package names. See for example Perl::Critic::Policy::NamingConventions::Capitalization

Upvotes: 3

hillu
hillu

Reputation: 9611

Your problem has nothing to do with the file that the variable was declared in, but with the namespace you put it in using the package keyword. Also, make sure that your namespaces don't start with a number. From perlmod(1):

Only identifiers starting with letters (or underscore) are stored in a package's symbol table.

Upvotes: 1

Related Questions