module for generic tag processing/formatting

Discussion in 'Perl Misc' started by Morty Abzug, Jan 25, 2013.

  1. Morty Abzug

    Morty Abzug Guest

    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 something? Or should I genericize my current code and publish it?

    The idea is to do something like this:

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

    Does something like this already exist? I'd prefer not to reinvent the wheel if at all possible. I can't find it on CPAN, but maybe I'm not looking hard enough.
    Morty Abzug, Jan 25, 2013
    1. Advertisements

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

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

    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->{$1}/g;
    return $s;

    package main;

    my $fmt = Formatter->new(h => 'red-sonja');
    print $fmt->format("Host %h\n");
    Rainer Weikusat, Jan 25, 2013
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.