Perl - Global variables available in all included scripts and modules?

旧时模样 提交于 2019-12-03 01:56:41

You can declare global variables with the our keyword:

our $var = 42;

Each global variable has a fully qualified name which can be used to access it from anywhere. The full name is the package name plus the variable name. If you haven't yet declared a package at that point, you are in package main, which can be shortened to a leading ::. So the above variable has the names

$var       # inside package main
$main::var # This is most obvious
$::var     # This may be a good compromise

If we had used another package, the prefix would change, e.g.

package Foo;
our $bar = "baz";
# $Foo::bar from anywhere,
# or even $::Foo::bar or $main::Foo::bar

If we want to use a variable without the prefix, but under other packages, we have to export it. This is usually done by subclassing Exporter, see @Davids answer. However, this can only provide variables from packages that are being used, not the other way round. E.g.

Foo.pm:

package Foo;
use strict; use warnings;
use parent 'Exporter'; # imports and subclasses Exporter

our $var = 42;
our $not_exported = "don't look at me";

our @EXPORT = qw($var); # put stuff here you want to export
# put vars into @EXPORT_OK that will be exported on request

1;

script.pl:

#!/usr/bin/perl
# this is implicitly package main
use Foo; # imports $var

print "var = $var\n"; # access the variable without prefix
print "$Foo::not_exported\n"; # access non-exported var with full name

Lexical variables (declared with my) don't have globally unique names and can't be accessed outside their static scope. They also can't be used with Exporter.

The easiest way to do this, would be to create your own module. So, for example, if I want global access to variables $foo and $bar, then I could create a module, as follows:

# file:  MyVars.pm
package MyVars;

$foo = 12;
$bar = 117.8;

1;

Then I can access these variables using any perl script that uses the MyVars module:

# file:  printvars.pl
use MyVars;

print "foo = $MyVars::foo\nbar = $MyVars::bar\n";

Output:

foo = 12
bar = 117.8
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!