Hacks 28-42
Perhaps the greatest invention of Perl 5 is the idea of modules. They allow people to modify the language and reuse code far beyond what Larry and the Perl 5 porters ever envisioned. (Who could have predicted CPAN or Acme::*
, for example?)
If you're doing any serious work with Perl, you'll spend a lot of time working with modules: installing them, upgrading them, loading them, working around weird and unhelpful features, and even distributing them. It makes a lot of sense to understand how Perl and modules interact and how to work with them effectively.
Here are several ideas that show off the varied ways that you can extend your programs. CPAN is only an arm's length away. Be ready.
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.
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.
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 });
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
.
Get Perl Hacks now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.