Re: export variables



On Dec 29, 2007 8:32 PM, <jwaixs@xxxxxxxxx> wrote:
Hello,

Could someone tell me if this is possible and if it is how I do it. I
have the following two file;

file1.pl
---
print "$testvar\n";
---

file2.pl
---
my $testvar = 37;
use "file1.pl";
---

If I run file2.pl (perl file2.pl) I will of course only see a newline.
But is it possible to export the testvar to file1.pl?


Hi,

You can do what you wanted by declaring the variable $testvar with 'our':

$ cat t1.pl

print $testvar;

$ cat t2.pl
use strict;
our $testvar = 123;
require 't1.pl';

$ perl t2.pl
123


But wait, this way above is not good practice in perl programming.
You'd better write something like below:

$ cat t1.pl

sub myprint {
print $testvar;
}
1;

$ cat t2.pl
use strict;
require 't1.pl';
our $testvar = 123;

myprint();

$ perl t2.pl
123

Surely this is one way I showed. There are more ways to do it,like
using the OO,etc.
.



Relevant Pages