perlmeditation
Dallaylaen
<p>I tend to use perl one-liners extensively, mostly for testing purposes. In particular, I often load a module with a loooooooooong name only to instantiate it once. And it's boooooooring to type the whole name twice.</p>
<p>So I came up with an idea of a one-liner shortener along the lines of:</p>
<code>
perl -we 'use new qw(My::Very::Long::Module x foo 42); print $x->get_foo;'
</code>
Which is a rough equivalent of
<code>
perl -we 'use My::Very::Long::Module; our $x = My::Very::Long::Module->new( foo => 42 ); print $x->get_foo;'
</code>
<p>And I have a proof-of-concept implementation that works as follows: </p>
<ul>
<li>require module being called;</li>
<li>create a new instance;</li>
<li>create a package variable in the calling package (so that strict doesn't complain);</li>
<li>set that variable to instance from above.</li>
</ul>
<p>Here it is.</p>
<code>
package new;
use strict;
use warnings;
=head1 NAME
new - shorted require Foo; Foo->new(...) to just one call
=head1 SYNOPSYS
use new qw(My::Very::Long::Module x foo 42);
is an exact equivalent of
our $x;
BEGIN {
require My::Very::Long::Module;
$x = My::Very::Long::Module->new( foo => 42 );
};
or a rough equivalent of
use My::Very::Long::Module;
our $x = My::Very::Long::Module->new( foo => 42 );
Not a big deal in a real program, but may save some typing in a
one-liner test script.
Works well under C<use strict;>.
=cut
$Carp::Internal{ (__PACKAGE__) }++;
sub import {
my ($self, $target, $name, @args) = @_;
my $filename = $target;
$filename =~ s#::#/#g;
$filename .= ".pm";
require $filename;
my $obj = $target->new( @args );
my $caller = caller;
$name ||= 'new';
my $sym = join "::", $caller, $name;
no strict qw(refs vars);
*$sym = \$$sym;
$$sym = $obj;
};
1;
</code>
<p>Made purely for fun, but maybe there's some point in it after all.</p>
<p><b>UPDATE</b> Available as <a href="https://gist.github.com/dallaylaen/206a649ea54db4c6db93e99a2e9514b0">gist</a>.