Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing value of a global variable using require?

Tags:

perl

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";
like image 546
made_in_india Avatar asked May 06 '12 12:05

made_in_india


People also ask

Can a global variable be accessed by any function?

Global variables can be used by everyone, both inside of functions and outside.

How would one access a global variable named foo?

In browser-based JavaScript, you can do something like this: var foo = "foo"; (function() { var foo = "bar"; console. log(foo); // => "bar" console.

Can C++ function access global variables?

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.

How do you assign a value to a global variable in node JS?

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.


1 Answers

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.

like image 150
Michael Slade Avatar answered Oct 01 '22 11:10

Michael Slade