So, i’m a bit of a perl newb. Although I had something much more complicated going, i all of a sudden hit a roadblock and cannot figure out wtf is wrong with the code. I’ve simplified it so greatly that it’s only a very small fragment of code.
Test.pl
package Test;
sub new {
my ($class) = shift;
my $self = {
_attr => "asdfa"
};
bless $self, $class;
return $self;
}
sub log {
print "\nAccessed via class: ".$self->{_attr};
}
process.pl
#!/usr/bin/perl
do "Test.pl";
use strict;
use warnings;
use diagnostics;
my($test) = new Test();
$test->log;
print "\nAccessed via main: ".$test->{_attr};
I run process.pl and I get the following output
Accessed via class:
Accessed via main: asdfa
I also get the warning
Use of uninitialized value in
concatenation (.) or string at Test.pl
line 12 (#1)
(W uninitialized) An undefined value was used as if it were already
defined. It was interpreted as a “” or a 0, but maybe it was a mistake.
To suppress this warning assign a defined value to your variables.
So the problem is that $self is actually undefined. Why, I have no idea. Is this not the way to initialize an object?
The object instance is passed as the first argument to the method. The usual thing to do is to store it in a variable called
$self, but perl doesn’t set this up for you, you must do it yourself:Note that although you have defined
strictandwarningsin your main code, you haven’t intest.plwhich means that$selfwas silently created with an undefined value rather than throwing a compile error for using an undeclared variable.Furthermore, I would advise you to put
package Testinto a file calledTest.pm, add a true statement1;on its own at the end of the file, and call it by sayinguse Test;instead ofdo "test.pl". It’s a much cleaner way to write modular code in Perl.