Hack 28. Shorten Long Class Names


Type only what you need to type. You know what you mean.

Are you tired of using Perl classes with Really::Long::Package::Names::You::Cant::Remember? Use aliased and forget about them. This handy CPAN module creates short, easy-to-remember aliases for long class names.

The Hack

Given the hypothetical example just cited, use aliased to load the class and create an alias all at once:

use aliased 'Really::Long::Package::Names::You::Cant::Remember'; my $rem = Remember->new( );

When aliased loads a class, it automatically creates a constant subroutine, in the local name space named after the final part of the package name. This subroutine returns the full package name. Because it's a constant, it's actually very efficient; Perl will inline the package name, so that by the time your code has compiled, Perl sees it as if you had actually typed:

use aliased 'Really::Long::Package::Names::You::Cant::Remember'; my $rem = Really::Long::Package::Names::You::Cant::Remember->new( );

You gain simplicity and lose, well, nothing.

Resolve conflicts

Sometimes you might want to alias two classes that have the same final portion of their package names. In such cases, specify the alias that you want to use to disambiguate the two classes:

use aliased 'My::App::Contact'; use aliased 'My::App::Type::Contact' => 'ContactType'; my $contact_type = ContactType->new( ); my $contact      = Contact->new({ type => $contact_type });

Importing with aliased

Sometimes, even in object-oriented programming, you need to import symbols from a module. aliased allows you to do so while still creating an alias. The only wrinkle is that you must explicitly specify an alias. Why? Because then you pass in a list of import symbols, and if you didn't specify an alias name, the first symbol would be the alias! Here's how it works:

use aliased 'My::App::Contact' => 'Contact', qw( EMAIL PHONE ); my $contact = Contact->new({     kind  => EMAIL,     value => 'perlhacks@oreilly.com', });

If you hadn't put that 'Contact' there, then the alias would have been EMAIL and that wouldn't do what you meant .



Perl Hacks
Perl Hacks: Tips & Tools for Programming, Debugging, and Surviving
ISBN: 0596526741
EAN: 2147483647
Year: 2004
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net