Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share/export a global variable between two different perl scripts?

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?

like image 784
Cthar Avatar asked Dec 28 '10 05:12

Cthar


People also ask

How do I export a variable in perl?

For a module to export one or more identifiers into a caller's namespace, it must: use the Exporter module, which is part of the standard Perl distribution, declare the module to inherit Exporter's capabilities, by setting the variable @ISA (see Section 7.3. 1) to equal ('Exporter'), and.

What is the difference between export and Export_ok in perl?

The difference is really a matter of who controls what gets into the use r's namespace: if you use @EXPORT then the module being use d does, if you use @EXPORT_OK then the code doing the import controls their own namespace.

How do I import a perl file into another perl file?

if you use “use” your file should be named with a . pm extension and placed in the same folder as the main perl script: use Filename; or you can use the “use lib” pragma to add modules to the @INC array and put them in any folder you want as long as you tell “lib” where you put your modules.


1 Answers

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.

like image 92
Eric Strom Avatar answered Sep 25 '22 12:09

Eric Strom