Wednesday, December 29, 2010

export a global variable between two different perl scripts

Method 1:

They will share global variables, yes. Are you seeing some problem with that?

Example:

first.pl:

#!/usr/bin/perl

use strict;
use warnings;

our (@a, @b);

@a = 1..3;
@b = "a".."c";

second.pl:

#!/usr/bin/perl

use strict;
use warnings;

require "first.pl";

our (@a,@b);
print @a;
print @b;

Giving:

$ perl second.pl
123abc





Method 2:

#!/usr/bin/perl

package My::Module;  # saved as My/Module.pm
use strict;
use warnings;

use Exporter;
our @ISA = 'Exporter';
our @EXPORT = qw(@a @b);

our (@a, @b);

@a = 1..3;
@b = "a".."c";

and then to use the module:

#!/usr/bin/perl

use strict;
use warnings;

use My::Module;  # imports / declares the two variables

print @a;
print @b;

That use line actually means:

BEGIN {
    require "My/Module.pm";
    My::Module->import();
}

The import method comes from Exporter. When it is called, it will export the variables in the @EXPORT array into the calling code.

SOURCE: STOCKOVERFLOW

No comments: