Connecting Tech Pros Worldwide Help | Site Map

How to declare global variables.

shrek123's Avatar
Newbie
 
Join Date: Aug 2007
Posts: 23
#1: Oct 22 '07
hi,

I am designing some code to communicate beetween two machines.
I want to declare variable (constants) into some seperate perl file and use them into all the perl scripts. I am confused how can I do this.
Do I need to create .pm file ? if yes please explain how can I create .pm file from .pl file.

Thanks in advance.
eWish's Avatar
Moderator
 
Join Date: Jul 2007
Location: Arkansas
Posts: 900
#2: Oct 22 '07

re: How to declare global variables.


perldoc -Constant

HTH
shrek123's Avatar
Newbie
 
Join Date: Aug 2007
Posts: 23
#3: Oct 22 '07

re: How to declare global variables.


Quote:

Originally Posted by eWish

perldoc -Constant

HTH

I am not clear, how can I use some constant defined in some package in more then one perl script.

Also I am not clear how can I create a package with constant declaration.

Could you please expain it via some example.

Thanks
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#4: Oct 22 '07

re: How to declare global variables.


Quote:
Constants belong to the package they are defined in. To refer to a constant defined in another package, specify the full package name, as in Some::Package::CONSTANT.
quoted from the CONSTANT manpage
shrek123's Avatar
Newbie
 
Join Date: Aug 2007
Posts: 23
#5: Oct 23 '07

re: How to declare global variables.


Quote:

Originally Posted by KevinADC

quoted from the CONSTANT manpage

Still I am not confident enough to code this. Here is what I wanna do:

I have a perl file "lib.pl" and it contain:

Expand|Select|Wrap|Line Numbers
  1.  
  2. use strict;
  3. our $somevariable = "It is Constant";
  4.  
I have another perl file "test.pl"
Expand|Select|Wrap|Line Numbers
  1.  
  2. use strict;
  3. my $x = $somevariable ; 
  4. print $x; # It should print It is Constant.
  5.  
  6.  
Please help me in getting the concept clear.

Thanks.
eWish's Avatar
Moderator
 
Join Date: Jul 2007
Location: Arkansas
Posts: 900
#6: Oct 23 '07

re: How to declare global variables.


Here is one way you can do this.

Config.pm
Expand|Select|Wrap|Line Numbers
  1. package My::Config;
  2. use base Exporter; 
  3.  
  4. our @EXPORT = qw(%config_vars);
  5. our @EXPORT_OK = qw(%config_vars);
  6.  
  7. our %config_vars = (some_var    =>    'Hello',
  8.                     another_var =>     'World'
  9.                 );
  10.  
  11.  
  12. 1;
In your script add these two lines to your code to access the Config.pm file.
Expand|Select|Wrap|Line Numbers
  1. use lib '/path/to/file/lib/';
  2. use My::Config;
Then you can use $config_vars{'some_var'} and $config_vars{'another_var'} in your script where you want to.

Or you can use require. Which I showed an example in another thread.
Reply