In Java, constructors are named the same thing as the package they are part of, so objects are created like this:

Object obj = new Object( param1, param2 );

You can get a similar syntax using Perl's indirect object syntax (though this syntax should probably be avoided):

my $obj = new Object( $param1, $param2 );

With a trick using the Exporter, we can get rid of the new completely. Here's an example:

package Constructor; use strict; use warnings; use Exporter; BEGIN { our @ISA; push @ISA, 'Exporter'; our @EXPORT = qw( ); our @EXPORT_OK = qw( ); } sub import { my $class = shift; my ($package, $filename, $line) = caller; no strict 'refs'; my $slot = $package . '::' . $class; # Input fields to our constructor my @FIELDS = qw( foo bar baz ); *$slot = sub { my $in_class = shift; my $params; if(ref($in_class) eq 'HASH') { $params = $in_class; $in_class = $class; } else { $params = shift || { }; } my $self = { map { $_ => $params->{$_} || '' } @FIELDS + }; bless $self, $class; }; } 1;

Here's a one-liner that demonstrates its use:

$ perl -MData::Dumper -I. -MConstructor -le '$obj = Constructor({ foo +=> 1 }); print Data::Dumper::Dumper($obj);' $VAR1 = bless( { 'bar' => '', 'baz' => '', 'foo' => 1 }, 'Constructor' );

Of course, this is an export-by-default in disguise. It is probably better if the import() routine allowed for conditional importing of this syntax. Doing this is left as an exercise to the reader.

I also forgo any promises that this will be readable in real-world programs :)

----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer

:(){ :|:&};:

Note: All code is untested, unless otherwise stated

Replies are listed 'Best First'.
•Re: Constructors Without ->new()
by merlyn (Sage) on Oct 23, 2003 at 15:08 UTC
    This would make it impossible to have class methods, only instance methods. However, if you don't mind creating new null objects every time you want to call a "class method", I guess that's OK.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      Now now, never say never. Especially not when it comes to Perl.

      It's quite right that Constructor->foo will resolve to Constructor()->foo, but that's not the only way to call a class method. Both

        Constructor::->foo

      and

        'Constructor'->foo

      will be "class method invocation".

      I even prefer to use Constructor::->foo over the one without colons, for reasons explained in Re: Capitalized subroutine names and packages.

      ihb
        Ahh, OK. Cool. I don't like having to call with an explicit hashref though. Maybe make it take a list and turn into a hash if it's not already a hashref. Maybe it does that already... dunno... I'm on a cellmodem link right now and didn't look.

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.

Re: Constructors Without ->new()
by jryan (Vicar) on Oct 23, 2003 at 15:48 UTC

    Very nice, I like it.

    Also, since you don't use $filename and $line, you might as well call caller in scalar context:

    my $package = caller;

    But that's just a very minor nitpick. :)

Re: Constructors Without ->new()
by dragonchild (Archbishop) on Oct 25, 2003 at 02:09 UTC
    Why are you using Exporter? You don't need it. import() is called during use anyways.

    ------
    We are the carpenters and bricklayers of the Information Age.

    The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

    ... strings and arrays will suffice. As they are easily available as native data types in any sane language, ... - blokhead, speaking on evolutionary algorithms

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.