Skip to content

Instantly share code, notes, and snippets.

@dallaylaen
Last active December 25, 2016 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dallaylaen/206a649ea54db4c6db93e99a2e9514b0 to your computer and use it in GitHub Desktop.
Save dallaylaen/206a649ea54db4c6db93e99a2e9514b0 to your computer and use it in GitHub Desktop.
A funny module to abbreviate perl one-liners
package new;
use strict;
use warnings;
our $VERSION = 0.01;
=head1 NAME
new - shortens require Foo; Foo->new(...) to just one call
=head1 SYNOPSYS
use new qw(x=My::Very::Long::Module 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
use Carp;
$Carp::Internal{ (__PACKAGE__) }++;
my $id = qr/[A-Za-z_][A-Za-z_0-9]*/;
my $mod = qr/$id(?:::$id)*/;
sub import {
my ($self, $target, @args) = @_;
$target =~ /(?:($id)=)?($mod)(?:\.($id))?/
or croak "new: first argument must be var=Module::Name.method";
my $name = $1 || 'new';
$target = $2;
my $method = $3 || 'new';
my $filename = $target;
$filename =~ s#::#/#g;
$filename .= ".pm";
require $filename;
my $obj = $target->$method( @args );
my $caller = caller;
$name ||= 'new';
my $sym = join "::", $caller, $name;
no strict qw(refs vars);
*$sym = \$$sym;
$$sym = $obj;
};
=head1 COPYRIGHT AND LICENSE
Copyright (c) 2016 Konstantin S. Uvarin <khedin@gmail.com>
This module is available on the same terms aas Perl itself.
=cut
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment