1

I can have a constructor like this :

sub create {
  my $class = shift;
  my $self  = {};
  return bless $self,$class;
}

and when I create an object, I can write this:

my $object = create Object;

Is this:

my $object = Object::create("Object");

the only equivalent to that constructor call?

Brad Gilbert
  • 33,846
  • 11
  • 78
  • 129
Geo
  • 93,257
  • 117
  • 344
  • 520
  • 1
    You don't have to use `
    $object
    ` just put four spaces in front of the code block, or better yet just select it, and press **`[Ctrl]`** + **`[K]`** .
    – Brad Gilbert Sep 01 '09 at 21:04
  • 2
    It's a very common convention to use `new` as the name of your constructor. Yeah, you could call it `chew_toenail_clippings` if you wanted to and it would work, but that's hardly mnemonic (if a bit gross). Also, you may wish to investigate Moose (http://moose.perl.org/), it is a very powerful OO system for Perl that will save you typing tons of redundant code (see the 'unsweetened' example: http://search.cpan.org/dist/Moose/lib/Moose/Manual/Unsweetened.pod ) – daotoad Sep 01 '09 at 23:20

1 Answers1

5

No, the equivalent call is

my $object = Object->create();

If you use the fully qualified name of the create function without the arrow syntax, you aren't going through Perl's OO method dispatch, and therefore any inherited methods will not work.

The arrow syntax is preferred over the "indirect" create Object syntax. For the reasons why, see this question.

Community
  • 1
  • 1
friedo
  • 65,762
  • 16
  • 114
  • 184
  • could you tell me all the equivalent calls? I don't care about the side effects of each, just the syntax. – Geo Sep 01 '09 at 20:49
  • The indirect `new Object` and arrow syntax `Object->new` are equivalent, except for the syntax ambiguity problems I mentioned with the indirect form. The only other way to call a function in another package is with its fully-qualified name, e.g. `Object::new()` which behaves exactly the same as calling `new()` in the current package. – friedo Sep 01 '09 at 22:41