24 days of Perl code from RJBS! Feed

More Stuff I Stole from Catalyst (that they stole back)

String::RewritePrefix - 2009-12-16

I Hate Typing

It's true. The only time that I like typing is when I'm playing Typing of the Dead. (I try to get in a big dose of zombie video games every Yuletide; maybe I'll bring the old Dreamcast up again this winter.) Apart from shooting zombies by typing quickly, typing stinks. It hurts my hands, and I live in perpetual dread of the day when I must find a new profession because my fingers no longer work. That's why most of the code I write is meant to save keystrokes for when I write other code.

Catalyst lets you write something like this in your config for Holiday::Web:


1: 
2: 
3: 
4: 
5: 

 

my $config = {
  'Model::GreetingCard' => { ... }
  'View::TextTemplate' => { ... }
  '+Catalyst::Plugin::Kwanzaa' => { ... }
}

 

The first two get rewritten to "Holiday::Web::Model::GreetingCard" and "Holiday::Web::View::TextTemplate" respectively. In the third, the + means that it should be used literally -- so just the plus sign is dropped. There's also a ~ prefix for slightly more arcane uses. Obviously, this can save a lot of typing and, just as importantly, a lot of reading. I liked this!

I really wanted to use this kind of rewriting for Dist::Zilla, and to make sure I could re-use this pattern whenever I wanted, I wrote String::RewritePrefix. Catalyst's behavior could be written as:


1: 
2: 
3: 
4: 
5: 
6: 

 

use String::RewritePrefix rewrite => {
  prefixes => {
    '' => 'Holiday::Web::',
    '+' => ''
  },
};

 

That's using Sub::Exporter, of course, so we can import a few rewriting strategies:


1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
10: 
11: 
12: 
13: 
14: 

 

use String::RewritePrefix
  rewrite => { -as => 'holiday_px', prefixes => { '' => 'Holiday::Web::', '+' => '' } },
  rewrite => { -as => 'num_px', prefixes => { '-' => 'negative ', '+' => 'positive ' } };

my @numbers = num_px( qw( +40 -10 +18 0 ) );
# ==> (positive 40, negative 10, positive 18, 0)

my @plugins = holiday_px( qw(
  Model::GreetingCard
  View::TextTemplate
  +Catalyst::Plugin::Kwanzaa
)
);
# ==> (Holiday::Web::Mode::GreetingCard,
# Holiday::Web::View::TextTemplate, Catalyst::Plugin::Kwanzaa)

 

There isn't much more to it, apart from one or two weird options. Still, think of all the typing and squinting you save in your config files!

The prefix rewriting in Catalyst::Utils, which inspired me to write String::RewritePrefix, now uses String::RewritePrefix! It's always a joy to find out that other people benefit from my attempt to be lazy and type less. It means they have more time for Typing of the Dead, too.

See Also