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

前端 未结 2 1458
眼角桃花
眼角桃花 2020-12-30 04:01

So lets say I have a main.pl script and in that script I need to declare some variables (any kind of variable constant or normal) and those variables need to be

相关标签:
2条回答
  • 2020-12-30 04:28

    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.

    0 讨论(0)
  • 2020-12-30 04:42

    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
    
    0 讨论(0)
提交回复
热议问题