in reply to OOP method usage

Also notice that the customary (required?) syntax is:   Test1->new().

The Perl implementation of objects is not quite what you might expect when coming from other languages.   But it is deceptively powerful, perhaps in part because it does not force you to do things in a certain way or make too many assumptions.

Replies are listed 'Best First'.
Re^2: OOP method usage
by tobyink (Canon) on Jul 07, 2012 at 19:00 UTC

    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'
      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.