2022 twenty-four merry days of Perl Feed

Let the Elves Import Your Packages

all - 2022-12-14

Same as every year, the last few days before Christmas are very busy for the Elves. Those little tinkers are best known for hand-crafting all the presents kids dreamed of, but they also run small but repetitive errands for Santa.

Did you know he doesn't need to manually import every single Perl package he has written? Yep, elves do that for him. It's effortless - he just whispers the namespace and his little helpers take care of the rest.

At around 2003, Santa managed to spy on the Elves to figure out how they do it. In his infinite generosity, he shared their method with some Perl module authors who later refined it. It was released to the world as EaaPM (Elves as a Perl Module) named all. Fourteen long years have passed since the method was perfected and Santa can still use this module without any issues, thanks to Perl's excellent backwards compatibility.

So, what was the method you might ask? Simple. You just had to write use all 'NAMESPACE'; and busy elves would go through your @INC recursively and import everything they found under that namespace. They had one significant limitation though - no matter how much they practiced, they couldn't get the hang of importing symbols into the caller. You could tell it just wasn't their thing.

How can you benefit from the module? Let's say you have packages, which are all classes:



use Present::Toy;
use Present::ElectronicDevice;
use Present::BoardGame;
use Present::SportsEquipment;
use Present::Candy;
use Present::Book;


You can just replace all of those lines with one of the following, which will all do the same:



use all 'Present';
use all 'Present::*';
use all of => 'Present';


It's Straightforward, Stable and Santa-approved - 'S' x 3!

Before I go, let me tell you a story of little Timmy.

Timmy enjoyed programming, especially in Perl. He had his own personal project, on which he spent a lot of his free time. The project grew and grew, and Timmy had implemented self-made tools that would resemble the Elvish method. Little did he know, he had circular imports in his code.

One day Timmy stumbled upon all module while enjoying metacpan. "It's so old and unmaintained, but I'm going to try it anyway" he thought while finding and replacing all his in-house code. When his tests all failed, he searched for two hours trying to figure out what was wrong with the module.

But the module wasn't broken. Funnily enough, it was his code that was to blame and the module just made it visible. Timmy humbly fixed his architecture and had more confidence in his code ever since. You see, the way Elves work may seem sloppy at first glance, but they actually do their work very well. The moral of the story is: don't fix something that isn't broken, especially if actual magic is involved.

Gravatar Image This article contributed by: Bartosz Jarzyna <bbrtj.pro@gmail.com>