Aliasing module names

brian_d_foy on 2005-08-12T20:55:50

I needed to cconvert some ISBNs without hyphens to those with hyphens. No problem: it's just a command line:

$ perl -MBusiness::ISBN -le 'print Business::ISBN->new(shift)->as_string' 1932394508 


I hate typing out that long module name more than once, though. Don't tell me about cut-n-paste since that takes my fingers off the keyboard (ore requires too much work).

I want to alias the package name. I could use Package::Alias, but that's a lot of typing too, especially since I still have to pull in the package myself still.

$ perl -MPackage::Alias=A,Business::ISBN -MBusiness::ISBN -le 'print A->new(shift)->as_string' 1932394508


I took Package::Alias (hey, it's open source!) and rewrote it (all 10 lines or so), to automatically pull in the modules it's aliasing. I called it "As", because I wanted something like SQL's "AS". It doesn't really make sense as a name because it comes in the wrong place.

$ perl -MAs=A,Business::ISBN -le 'print A->new(shift)->as_string' 1932394508


So, it's a little bit shorter, and it works. So far.

What I'd like to write, however, is something with an equal sign, but that's the shortcut for the import list. I could make the import function realize that I want an alias, but then I have to do that everywhere, and that's not right.

$ perl -MBusiness::ISBN=A -le 'print A->new(shift)->as_string' 1932394508


I thought about some magic that would figure it out. Instead of picking the alias name, I let the As module do it for me. However, I end up stomping all over As.pm. That's fine, really, because I don't need any of that stuff after I use it. Yeah, how often have you heard that one?

$ perl -MAs=Business::ISBN -le 'print As->new(shift)->as_string' 1932394508


At that point I got bored and stop thinking about it.


use aliased 'Business::ISBN';

Ovid on 2005-08-12T21:11:04

I'm not fond of the Package::Alias module because you have to alias one namespace to another and I really don't like futzing around with namespaces. Instead, you might find my "aliased" module interesting. It exports a constant subroutine and you can just use that (it also supports renaming on the fly or importing, if need be).

use aliased 'Business::ISBN';
my $isbn = ISBN->new;

shell functions

Dom2 on 2005-08-12T23:46:28

The long command line doesn't matter too much. If you're going to use it more than once, wrap it in a shell function to give it a shorter name.
isbn () { perl ... $1 }

And then it just becomes isbn 1234567890 instead each time.

If it's still useful after this shell session, put it in a file in ~/bin I guess...

-Dom

Re:shell functions

brian_d_foy on 2005-08-13T01:04:13

Yeah, that solves it for that instance, but I want a general solution I can apply to any one-liner.