Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the two statements always the same in perl?

Tags:

oop

perl

$obj->SUPER::promote();

$obj->SUPER->promote();

Anyone knows if they're the same?

like image 379
compile-fan Avatar asked Jun 25 '11 16:06

compile-fan


People also ask

What does =~ mean in Perl?

=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {


1 Answers

No. The -> operator means call a reference (in this case, an object reference), and it will look for the SUPER method, not the super base class.

Here is code to show it:

#!/usr/bin/perl -w

package MyOBJ;

use strict;
use warnings;

use Data::Dumper;

sub new {
    my ($class) = @_;

    my $self = {};

    bless $self, $class;

    return $self;
}

sub promote {
    my ($self) = @_;

    print Dumper($self);

}

1;

package MyOBJ::Sub;

use strict;
use warnings;

use base 'MyOBJ';

1;

use strict;
use warnings;

my $obj = MyOBJ::Sub->new();

$obj->SUPER::promote();

Run it, you'll get:

$VAR1 = bless( {}, 'MyOBJ::Sub' );

When you change the last line to use -> instead of :: you get:

Can't locate object method "SUPER" via package "MyOBJ" at test.pl line 45.

From the "perldoc perlop" manual

The Arrow Operator

If the right side is either a "[...]", "{...}", or a "(...)" subscript, then the left side must be either a hard or symbolic reference to an array, a hash, or a subroutine respectively.

Otherwise, the right side is a method name or a simple scalar variable containing either the method name or a subroutine reference, and the left side must be either an object (a blessed reference) or a class name (that is, a package name)

Since the left side is neither an object ref or a class name (SUPER is a language defined bareword for polymorphism), it's treated as a method, which doesn't exist, hence the error.

like image 163
Corey Henderson Avatar answered Sep 28 '22 01:09

Corey Henderson