May 8, 2013

Eponymous Hash

You've been there.

Coding along, minding your own business, creating clear and concise lines of Perl code with maps, greps, and slices; manipulating lists with the best of them.

Suddenly, you find yourself doing this:

method_name(
  ponycorn => $ponycorn,
  sparkles => $sparkles
);

Immediately, you're offended. The sheer arrogance of this method hurts your soul. All that retyping of the same thing.

You stare at it, convinced you can fix it with some sort of list manipulation. You work through several permutations in your head, until you realize that you either have to make the code unreadable, or you have to settle for duplicating the names - once in the key, once in the value.

Years go by. You run into the same issue again and again.

We've all been there.

But no more. Now, there is Eponymous::Hash.*

Eponymous::Hash will examine your list of scalars, array refs, and hash refs, and return a hash with keys matching your variable names.

Given these declarations:

my $ponycorn  = 'jello';
my $sparkles  = 'pudding';

This statement:

eponymous_hash($ponycorn, $sparkles)

Returns this hash:

(ponycorn => 'jello', sparkles => 'pudding')

Now, you might be thinking,

1) What does eponymous mean, and 2) why do I have to type so long a name?

Excellent questions.

  1. Don't worry about it.
  2. You don't.

You can define your own method name, as short or long as you want:

use Eponymous::Hash 'epy';

method_name(epy $ponycorn, $sparkles);

Should something like this be built-in to Perl? Yes. But until then, there's Eponymous::Hash.

* There might already be solutions to this. If there are, I bet none of them mention ponycorns in their POD. Huzzah!
comments powered by Disqus