Is it possible to access value of a global variable declared, in another perl script using require?
eg.
Config.pl
#!/usr/bin/perl
use warnings;
use strict;
our $test = "stackoverflow"
Main.pl
#!/usr/bin/perl
use warnings;
use stricts;
require "Config.pl"
print "$test\n";
print "$config::test\n";
Global variables can be used by everyone, both inside of functions and outside.
In browser-based JavaScript, you can do something like this: var foo = "foo"; (function() { var foo = "bar"; console. log(foo); // => "bar" console.
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function.
To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value.
sure. The way you have suggested almost works. Try:
Config.pl
:
use warnings;
use strict;
our $test = "stackoverflow";
and the main program:
#!/usr/bin/perl
use warnings;
use strict;
require "Config.pl";
our $test;
print "$test\n";
When you call require
, the file is executed in the same namespace as the caller. So without any namespaces or my
declarations any variables assigned will be globals, and will be visible to the script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With