Perl - Global variables available in all included scripts and modules? -
so lets have main.pl
script , in script need declare variables (any kind of variable constant or normal) , variables need available through scripts , modules i'll include main.pl
script automatically.
what mean if have variable $myvar
in main.pl
, main.pl
require script1.pl
, script2.pl
or script3.pm
, , of scripts need access $myvar
access var defined in specific script or module.
i've searched on net, i've found examples can access variables scripts include or extract variables modules; that's not want.
isn't there keyword in php use global $var1, $var2
etc. use variable parent script?
any example, documentation or article acceptable - me accomplish helpful.
you can declare global variables our
keyword:
our $var = 42;
each global variable has qualified name can used access anywhere. full name package name plus variable name. if haven't yet declared package @ point, in package main
, can shortened leading ::
. above variable has names
$var # inside package main $main::var # obvious $::var # may compromise
if had used package, prefix change, e.g.
package foo; our $bar = "baz"; # $foo::bar anywhere, # or $::foo::bar or $main::foo::bar
if want use variable without prefix, under other packages, have export it. done subclassing exporter
, see @davids answer. however, can provide variables packages being use
d, not other way round. e.g.
foo.pm
:
package foo; use strict; use warnings; use parent 'exporter'; # imports , subclasses exporter our $var = 42; our $not_exported = "don't @ me"; our @export = qw($var); # put stuff here want export # put vars @export_ok exported on request 1;
script.pl
:
#!/usr/bin/perl # implicitly package main use foo; # imports $var print "var = $var\n"; # access variable without prefix print "$foo::not_exported\n"; # access non-exported var full name
lexical variables (declared my
) don't have globally unique names , can't accessed outside static scope. can't used exporter
.
Comments
Post a Comment