Perl: how to make variables from requiring script available in required script

后端 未结 2 1228
南方客
南方客 2021-01-06 04:18

example

out.pl:

(my|our|local|global|whatever???) var = \"test\";
require(\"inside.pm\");

inside.pm:

print $var;
         


        
2条回答
  •  时光取名叫无心
    2021-01-06 05:08

    It will work with our.

    $ cat out.pl
    our $var = "test";
    require("inside.pm");
    
    $ cat inside.pm 
    print "Testing...\n";
    print "$var\n";
    
    $ perl out.pl
    Testing...
    test
    

    This works because our makes $var global, and inside.pm is being executed in the scope with $var defined. Not sure it is recommended technique, but it is an interesting question nevertheless!

    EDIT: Need to clarify (okay patch) the answer based on a comment:

    From the documentation on the Perl function our:

    our associates a simple name with a package (read: global) variable in the current package, for use within the current lexical scope. In other words, our has the same scoping rules as my or state, but does not necessarily create a variable.

    So using our, we get $var with the current package (here probably main) and we can use it in its scope. In effect it is then "global" to the code in the file you are requiring-in.

    A true global is introduced without the our, because variables default to global. But I don't know anyone that would recommend them.

提交回复
热议问题