Create a gist now

Instantly share code, notes, and snippets.

@dallaylaen /
Last active Dec 25, 2016

What would you like to do?
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
use new qw(x=My::Very::Long::Module foo 42);
is an exact equivalent of
our $x;
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;>.
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;
Copyright (c) 2016 Konstantin S. Uvarin <>
This module is available on the same terms aas Perl itself.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment