module for generic tag processing/formatting

M

Morty Abzug

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.
 
R

Rainer Weikusat

Morty Abzug said:
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?

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");
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top