Follow this Blog!

Jan 25, 2010

f Comment

Perl: Define a Variable in One File and Access It from Another File!

Problem
Amazon I want to define a variable in one perl file and be able to access it from another perl file in the easiest and quickest way possible.

First of all I find it shocking that I couldn't find much support for this question on Google so I decided to post the answer myself.
By the way what we are doing is create the so-called global variables which are defined in one file and can be accessed in another file!
Solution
Suppose in global.pl you'd like to define the variable (or variables), and in access.pl you'd like to access the variables defined in global.pl. In global.pl define the variable. Do not use 'my' keyword, as it restricts the scope to current file. This means that you should NOT have 'use strict' in global.pl. In access.pl put "require 'global.pl'". That's it.

For example:

In global.pl you have:

$MY_GLOBAL_VARIABLE1 = 1;
$MY_GLOBAL_VARIABLE2 = 'a string';

In access.pl you have:

require 'global.pl';
print "My global variable 1 is $MY_GLOBAL_VARIABLE1 and my global variable 2 is $MY_GLOBAL_VARIABLE2";

Easy right? Hope it helps

If you have any questions let me know and I will do my best to help you!
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael