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.
So I came up with an idea of a one-liner shortener along the lines of:
perl -we 'use new qw(My::Very::Long::Module x foo 42); print $x->get_f
+oo;'
Which is a rough equivalent of
perl -we 'use My::Very::Long::Module; our $x = My::Very::Long::Module-
+>new( foo => 42 ); print $x->get_foo;'
And I have a proof-of-concept implementation that works as follows:
- require module being called;
- create a new instance;
- create a package variable in the calling package (so that strict doesn't complain);
- set that variable to instance from above.
Here it is.
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;
Made purely for fun, but maybe there's some point in it after all.
UPDATE Available as gist.