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


In reply to Constructors Without ->new() by hardburn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.