in reply to Re: OOP method usage
in thread OOP method usage

Actually, the following are equivalent:

my $object = MyClass->new; my $object = new MyClass;

The second is referred to as the "indirect object syntax". It's generally discouraged because it can confuse the perl parser.

Actually, the first syntax isn't fantastic either, because...

package MyClass { sub new { bless []=>shift } } package OtherClass { sub new { bless []=>shift } } package main { sub MyClass () { return 'OtherClass' } my $object = MyClass->new; print ref $object; }

Now, what does that print? You might expect $object to be an instance of MyClass, but it's actually an instance of OtherClass.

The following are unambiguous ways to call a constructor:

my $object = MyClass::->new; my $object = 'MyClass'->new; my $class = 'MyClass'; my $object = $class->new;

Back to the topic of the indirect object syntax... there's a module called indirect that allows you to convert uses of indirect object syntax into fatal errors.

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

Replies are listed 'Best First'.
Re^3: OOP method usage
by Anonymous Monk on Jul 08, 2012 at 20:44 UTC
    So, sometimes there are cases where there you ought to pick one way to do it ... and stick with that way forever. Grab any ol' Perl package that you have respect for, look inside to see how they do it, and do it that way.