Friday, November 13, 2020

Can't locate object method via package "1" (perhaps you forgot to load "1"?)

This Perl error means that when you use $obj->method() $obj == 1 instead of an instance of a Perl class. It doesn't work to do 1->my_method()

I triggered the error by failing to return $self from my constructor.

 

1 package NoError; 2 3 sub new { 4 my $class = shift; 5 my $self ={}; 6 bless $self,$class; 7 return $self; # the right way to do it 8 } 9 10 sub hi { return 'hi';} 11 12 1; 1 package OneError; 2 3 sub new { 4 my $class = shift; 5 my $self ={}; 6 bless $self,$class; # succeeds returns 1 7 } 8 9 sub hi { return 'hi';} 1 #!/usr/bin/perl 2 3 use FindBin; 4 use lib "$FindBin::Bin" ; 5 6 use OneError; 7 use NoError; 8 9 my $no_obj = NoError->new(); 10 print $no_obj->hi(), "\n"; # works fine new() 11 # returns $self 12 12 my $oe_obj = OneError->new(); 13 print $oe_obj->hi(), "\n"; # new() returns 1 14 # 1->hi() doesn't work

Gabor Szabo has a helpful blog about interpreting @_ in scalar context If you have $obj = @_; instead of ($obj) = @_; you get $obj == 1 , the number of elements in @_ rather than an actual object.

No comments:

Post a Comment