module for generic tag processing/formatting

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
One thing I've wanted a couple of times, and have coded once: a module for =
generic string processing/formatting.  I looked on CPAN, and don't see it. =
 I vaguely recall having seen something like this before.  Am I missing som=
ething?  Or should I genericize my current code and publish it?

The idea is to do something like this:

my $formatter=3Dnew String::Formatter(h=3D>"red-sonja", o=3D>"linux", r=3D>=
my $output=3D$formatter->format("Output for host %h\n"); # should yield "Ou=
tput for host red-sonja\n"

Does something like this already exist?  I'd prefer not to reinvent the whe=
el if at all possible.  I can't find it on CPAN, but maybe I'm not looking =
hard enough.

Re: module for generic tag processing/formatting

Quoted text here. Click to load it

This sounds like a template module. There are many on CPAN, though not
one I can think of with that syntax. I would recommend Template::Simple
for something simple like that, or TT2 (that is, the Template-Toolkit
and related distributions) for a rather complete solution.

Actually, now that I think of it, it might be possible to make
Template::Simple use that with a lookbehind; something like

    my $T = Template::Simple->new(
        pre_delim   => qr/%/,
        post_delim  => qr/(?<=.)/,

though TBH it's so simple I'd probably just use


If you want more complex sprintf-like formatting, you could look at


Re: module for generic tag processing/formatting

Quoted text here. Click to load it

Ehh ... yes ... it is called 'interpolating variables into a string',
in this case

%values = (h => 'red-sonia');
print "Output for host $values";

Unless you want something much more complicated than that,

package Formatter;

sub new
    my $class = shift;
    my %self;

    %self = @_;
    return bless(\%self, $class);

sub format
    my ($self, $s) = @_;

    $s =~ s/%([A-Za-z0-9_]+)/$self->/g;
    return $s;

package main;

my $fmt = Formatter->new(h => 'red-sonja');
print $fmt->format("Host %h\n");

it exists now.

Site Timeline