I’m modularizing my code, but when I move a sub out of it’s original module, I get the following error:
Couldn't load application from file "foo.pl": Not an ARRAY reference at D.pm line 10.
This was the original file. As is, it’s all ok:
FormerC.pm:
package FormerC;
use strict;
my %my_hash = ( key => 'value' );
my @my_array = qw( some strings inside array );
sub problematic_sub {
my ($hash_ref, $array_ref) = @_;
my @an_array = @$array_ref;
return \@an_array;
};
sub uses_problematic_sub {
problematic_sub(\%my_hash, \@my_array);
};
uses_problematic_sub();
1
These are the two new modules. With these I get the error:
D.pm:
package D;
use strict;
sub new { bless {}, shift };
sub problematic_sub {
my ($hash_ref, $array_ref) = @_;
my @an_array = @$array_ref;
return \@an_array;
};
1
C.pm:
package C;
use strict;
use D;
my $d = D->new;
my %my_hash = ( key => 'value' );
my @my_array = qw( some strings inside array );
sub uses_problematic_sub {
$d->problematic_sub(\%my_hash, \@my_array);
};
uses_problematic_sub();
1
You are likely to be better off using the
Exportermodule to export the subroutine names into the calling code’s namespace. What you have written here is an object-oriented module, but the object is just a collection of subroutines and doesn’t need object-oriented support.The problem is that a method call like
implicitly passes the object as the first parameter, so it is equivalent to
All you need to do is account for this in the subroutine
and your code should work.
Also note that a subroutine declaration, like a
whileorforloop, is not a statement and so doesn’t need and shouldn’t have a semicolon after it.