anaconda_wly has asked for the wisdom of the Perl Monks concerning the following question:

I saved all the following lines in one file test.pl and run and got an error(Can't call method "isExist" on an undefined value at test.pl line). Anyone may help point out my problem?Thanks;

The code:
package testor; my $componentName = ''; sub new{ $componentName = $_; } sub isExist{ return 0; } 1; #use testor; my $myComponent = '7-Zip 9.20 (x64 edition)'; my $checker = testor->new($myComponent); if( $checker->isExist() ){ print '$myComponent already installed\n'; }else{ print '$myComponent not installed\n'; } exit 1;

Replies are listed 'Best First'.
Re: newbie's question on inheritance
by tobyink (Canon) on Oct 28, 2012 at 06:43 UTC

    For this to work, you need new to return an object. Right now it just returns undef.

    Firstly, you need to read perlsub to learn how subs work, and the important difference between $_ and @_.

    Then turn to perlootut to learn the basics of object-oriented programming in Perl.

    Here's how you could write your code...

    use strict; use warnings; { package testor; sub new { my $class = shift; return bless { component_name => $_[0], }, $class; } sub component_name { my $self = shift; return $self->{component_name}; } sub isExist { my $self = shift; return 0; } } my $myComponent = '7-Zip 9.20 (x64 edition)'; my $checker = testor->new($myComponent); if( $checker->isExist ) { print $checker->component_name, " already installed\n"; } else { print $checker->component_name, " not installed\n"; }

    But personally I'd write it as...

    use strict; use warnings; { package testor; use Moo; has component_name => ( is => 'ro' ); sub isExist { my $self = shift; return 0; } } my $myComponent = '7-Zip 9.20 (x64 edition)'; my $checker = testor->new(component_name => $myComponent); if( $checker->isExist ) { print $checker->component_name, " already installed\n"; } else { print $checker->component_name, " not installed\n"; }

    Either way, read those bits of Perl documentation I mentioned, and learn why your original attempt is wrong.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      It's very kind of you. Thanks a lot!