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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |