Reputation: 859
If it is duplicate, say so. I Have not found it, only for PHP but for Perl. So If I can write full name of e.g. Class::sub()
or $Class::scalar
, I can write Class->sub
or $Class->scalar
(in case I have use
d or require
d the Class
), what is the main difference in perl?
The problem is: Class Animal.pm:
#!/usr/bin/perl -w
package Animal;
our $VERSION = '0.01';
sub speak {
my $class = shift;
print "a $class goes ", $class->sound;
}
sub sound{
die "You have to defined sound() in a subclass";
}
Then Class Horse.pm:
#!/usr/bin/perl -w
package Horse;
use Animal;
our @ISA = qw[Animal];
our $VERSION = '0.01';
sub sound { 'neight' }
1
And if I, in main program do this:
#!/usr/bin/perl -w
BEGIN{ unshift @INC, 'dirWithModules' }
use Horse; use Animal;use Cow;
Animal::speak('Horse');
output---->"a Horse goes neight"
BUT IF I OD
#!/usr/bin/perl -w
BEGIN{ unshift @INC, 'dirWithModules' }
use Horse; use Animal;use Cow;
Animal->speak('Horse')
output--->"You have to defined sound() in a subclass at Animal.pm"
So my question is, If I reference my method from class Horse.pm
iherited sub speak
from Animal.pm
with ::
, double colon, the NO PROBLEM - it will print the sound. However if I try to reference the sub with ->
arrow, The $class
is not inherited - that is, $class
is Animal.pm
itself, but not as parameter sent ('Horse'
). So In what is ::
and ->
different?
Upvotes: 4
Views: 1303
Reputation: 385655
Foo->bar()
is a method call.
It will pass the invocant (the left side of ->
) as the first argument. As such, bar
should be written as follows:
# Class method (Foo->bar)
sub bar {
my ($class, ...) = @_;
}
or
# Object method (my $foo = Foo->new; $foo->bar)
sub bar {
my ($self, ...) = @_;
}
Foo::bar()
is a sub call.
Upvotes: 6