Alex
Alex

Reputation: 10126

Defining global variable in Perl with `strict`

I have the following package/files structure: The first one:

# package1
package Package1;

use strict;
use warnings;

my @array = (1, 2, 3, 4);

return 1;

The second one:

use strict;
use warnings;
use package1;

foreach $a (@array)
{
    print $a;    
}

Unfortunately, I have the following error:

Global symbol "@array" requires explicit package name at Package1.pm

I tried to define @array as our, but it didn't help. Also I can not define it as just @array, because of strict.

Is there any legal way to make global variables with strict?

Upvotes: 2

Views: 2565

Answers (1)

Miguel Prz
Miguel Prz

Reputation: 13792

Package code: (our instead of my)

package Package1;

use strict;
use warnings;

our @array = (1, 2, 3, 4);

return 1;

script code:

use strict;
use warnings;
use Package1;

foreach my $a (@Package1::array)
{
    print $a;    
}

Also, you could use Exporter module to control the functions and variables into the user's namespace

Upvotes: 5

Related Questions