28

How do we share or export a global variable between two different perl scripts.

Here is the situation:

first.pl

#!/usr/bin/perl
use strict;
our (@a, @b);
.........

second.pl

#!/usr/bin/perl
use strict;
require first.pl;

I want to use global variable (@a, @b) declared in first.pl

Also,suppose there's a variable in second perl file same as first perl file. But I want to use first file's variable. How to achieve this?

3 Answers 3

35

In general, when you are working with multiple files, and importing variables or subroutines between them, you will find that requiring files ends up getting a bit complicated as your project grows. This is due to everything sharing a common namespace, but with some variables declared in some files but not others.

The usual way this is resolved in Perl is to create modules, and then import from those modules. In this case:

#!/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.

Looking at the documentation for Exporter and perlmod should give you a starting point.

Sign up to request clarification or add additional context in comments.

1 Comment

I recently noticed that Exporter's documentation suggests that we not do this, stating "Exporting variables is not a good idea. They can change under the hood, provoking horrible effects at-a-distance that are too hard to track and to fix. Trust me: they are not worth it." I've been using Perl for a long time—perhaps not competently—and this seems fine to me. What are your thoughts?
19

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

1 Comment

Thanks.... i missed to declare same variable in the second.pl. Initially, when it was not declared,it says, Variable "@a" is not imported at ..... It is working now...
2

Cant you use package and export the variable?

1 Comment

Thanks.... After this problem.... i am exploring the use of package. Thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.