Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: RFC: new.pm - a perl -e use/new shortener

by jdporter (Paladin)
on Dec 27, 2016 at 21:02 UTC ( [id://1178533]=note: print w/replies, xml ) Need Help??


in reply to RFC: new.pm - a perl -e use/new shortener

Nice idea! But I don't like the idea that you have to pass in the name of the variable to be assigned, for its consequence that it can't be a lexical variable.

The idea is to 'require' a module and invoke some method of it in one call, right?
Here's my take:

# package 'Factory', exports function 'fab' (short for "fabricate") package Factory; use base 'Exporter'; @EXPORT = qw( fab ); use Carp qw(croak); use strict; use warnings; sub fab($$@) { my $class_name = shift; my $ctor_name = shift; $class_name =~ /[^\w:]/ and croak; eval 'require '.$class_name; $class_name->$ctor_name(@_) } 1;

Use it in a one-liner:

perl -MFactory -le "my $x = fab 'My::Very::Long::Module', 'new', foo = +> 42; print $x->get_foo;"

Pedantry: Technically, Perl 5 (that is, its intrinsic object programming system) does not have constructors. What we typically name new are typically factory methods.
(I say "typically" because, by Wall, Perl gives you enough rope to shoot yourself in the foot.)

I reckon we are the only monastery ever to have a dungeon stuffed with 16,000 zombies.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1178533]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2024-03-28 20:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found