Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between double colon and arrow in perl

Tags:

perl

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 used or required 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?

like image 577
Herdsman Avatar asked Oct 30 '25 10:10

Herdsman


1 Answers

Foo->bar() is a method call.

  • It will use inheritance if necessary.
  • 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.

  • It won't use inheritance.
like image 168
ikegami Avatar answered Nov 01 '25 08:11

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!