Reference main variable in a package

Viewed 78

I want to create a library with methods A(), B(), and C() which will be called hundreds of times in each perl program with different strings as parameters. Each method updates its respective array (@A, @B, and @C) so I don't want to pass the array by reference each time. Each perl program also some unique strings they add to the array, so I cannot have the array be created and only modified by the package.

Is it possible to manipulate a shared array from the main program in a package without having to pass it through a subroutine? Is there a way to set an alias array or array pointer to reference the array in main?

main.pl

use MyPackage;
our @a;

MyPackage.pm

package MyPackage;
$alias_a = @main::a;
push @alias_a, "1";

OR

$aref = \@main::a;
push @$aref, "1";

edit: updated the OP with more background information.

1 Answers

That is the way global Variables are declared and used in Perl. In your main executable you can use

@main::a 

directly or (pre-)declare it with

our @a;

or

use vars q(@a);

and use it with @a in your main script.

When you are using this global variable in another package, you have to use the fully qualified form @main::a. Especially for global Variables declared in packages (other than main) there is the Exporter - package that allows you to import them in your own namespace, so you don't have to use the form @package::variable.

See https://perldoc.perl.org/Exporter.html, https://perldoc.perl.org/functions/our.html and https://perldoc.perl.org/vars.html for further explanations.

Related