Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Can't locate object method

Tags:

perl

This is my first time working with perl (v5.28.1). I'm getting the error:

'Can't locate object method "load" via stepReader (perhaps you forgot to load 'stepReader')'. 

When I print something in the file it works, but somehow my method can't be found.

I have stepReader.pm in a subdirectory called src

**

example.pm

use lib 'src/';
use stepReader;

@ISA = ('stepReader');

my $class = stepReader->load('assets/glasses.STEP');

stepReader.pm

package src::stepReader;

use strict;
use warnings;

sub load {  
    # Variable for file path
    my $filename = @_;
    # Open my file
    open(my $fh, '<:encoding(UTF-8)', $filename)
        or die "Could not open file '$filename' $!";

    # Print the file!
    while (my $row = <$fh>) {
        chomp $row;
        print "$row\n";
    }

    return bless {}, shift;
}

print "test if this works!";

1;

Output:

Can't locate object method "load" via package "stepReader" (perhaps you forgot to load "stepReader"?) at example.pm line 6.
test if this works!

I suspect this is something easy, but I hope someone can help me. Thanks in advance

like image 206
mHvNG Avatar asked Mar 04 '23 11:03

mHvNG


1 Answers

The immediate problem is that there is no class called stepReader in your code, only src::stepReader:

package src::stepReader;

That is, the function is called src::stepReader::load, not stepReader::load. Change the package declaration to:

package stepReader;

Also, module names that start with lowercase letters are informally reserved for pragmata. For normal modules the convention is to use an uppercase letter:

package StepReader;

(and rename the file StepReader.pm to match).


The parameter unpacking is broken, too:

    # Variable for file path
    my $filename = @_;

This puts the @_ array in scalar context, giving the number of elements. You want list assignment instead (with parentheses on the left-hand side), and method calls pass the invocant as an implicit first argument:

    my ($class, $filename) = @_;

    ...
    return bless {}, $class;

Alternatively:

    my $class = shift;
    my ($filename) = @_;

or

    my $class = shift;
    my $filename = shift;

You should always start your files with use strict; use warnings; or equivalent. It's currently missing from example.pm:

use strict;
use warnings;
use lib 'src';
use StepReader;

# This line is not needed, but if it were:
# our @ISA = ('StepReader');
like image 180
melpomene Avatar answered Mar 12 '23 12:03

melpomene