In Perl, how can I access a scalar defined in another package?

I seem to be stuck trying to access a scalar that is defined in another package and narrowed down the example to a simple test case where I can reproduce the problem. What I want to be able to do this refers to the list that is defined in the Example package, however, using our mechanism, Dumper shows that the variable is always undefined in example.pl:

Example. pm looks like this:

#!/usr/bin/perl -w

use strict;
use warnings;
use diagnostics;

package Example;
use Data::Dumper;

my $exported_array = [ 'one', 'two', 'three' ];
print Dumper $exported_array;

1;

And the code that uses this package is as follows:

#!/usr/bin/perl -w

use strict;
use warnings;
use diagnostics;
use Data::Dumper;

use lib '.';
use Example;

{ package Example;
  use Data::Dumper;
  our $exported_array;
  print Dumper $exported_array;
}

exit 0;

When this code is run, the first Dumper starts, and everything looks fine, after that the second Dumper, example.pl starts, and the link is undefined:

$VAR1 = [
          'one',
          'two',
          'three'
        ];
$VAR1 = undef;
+3
4

$exported_array Example, Example $exported_array main $exported_array - . - 1. my our Example .

our $exported_array;

...

print Dumper $Example::exported_array;

Example Exporter. ( Example::import, .)

package Example;
our $exported_array = ...;
our @EXPORT_OK = qw<$exported_array>;
use parent qw<Exporter>;

script:

use Example qw<$exported_array>;

, ( ), :

our @exported_array = (...);
our @EXPORT_OK      = qw<@exported_array>;
...
use Example qw<@exported_array>;
...
print Dumper( \@exported_array );
+5

my .

, ,

our $exported_array = [ ... ];

$Example::exported_array
+6

my, , , .

, - , our, . , - .pm, our $exported_array; .

+3

Exporter , , , ... . .

? , Moose?

.pm Moose - , .. . , - , : MOP ( Moose) - (aka sub {}). Data: Dumper script, , .

Example.pm

package Example;
use Moose;

has 'exported_array' => (is => 'rw', default => sub { [ 'one', 'two', 'three' ] });
1;

script:

example.pl

#!/usr/bin/env perl
use Modern::Perl '2013';
use lib '.';
use Example;
use Data::Dumper;

my $example = Example->new;
my $imported_array_ref = $example->exported_array;
my @imported_array = @{$imported_array_ref};
foreach my $element(@imported_array) { say $element; }
say Dumper(\@imported_array);

example.pl script ... , :

#!/usr/bin/env perl
use Modern::Perl '2013';
use lib '.';
use Example;
use Data::Dumper;

my $example = Example->new;
my @imported_array = @{$example->exported_array};
foreach my $element(@imported_array) { say $element; }
say Dumper(\@imported_array);

I think a lot more Perl programmers would cover Moose if there were simpler examples showing how to do simple things.

The official moose guide is great, but it really was written for those who are already familiar with OOP.

+1
source

Source: https://habr.com/ru/post/1779011/