Urthas has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

Consider the following code:
$bar = "Hello %s world!\n"; if ($bar =~ m/(Hello)/) { $foo = lc $1; $foo =~ s/h/j/; printf $bar, $foo; # prints "Hello jello world!" }
Now consider this twist on the idea of a placeholder:
$bar = "Hello $foo world!\n"; if ($bar =~ m/(Hello)/) { $foo = lc $1; $foo =~ s/h/j/; print "$foo\n"; # prints "jello" print $bar; # prints "Hello world!" }
Can I coerce Perl to DWIM? If so, how?

Thanks.

Replies are listed 'Best First'.
Re: placeholders without printf?
by ikegami (Patriarch) on Jan 23, 2010 at 03:29 UTC
    In both snippets, what $bar contains is a template. You're looking for a template system. String::Interpolate's interface is a bit weird, but it supports templates like the one you have in your second snippet.
      String::Interpolate's interface is a bit weird

      You weren't kidding. O.o

      Thanks again.

Re: placeholders without printf?
by Anonymous Monk on Jan 23, 2010 at 02:18 UTC
Re: placeholders without printf?
by graff (Chancellor) on Jan 23, 2010 at 16:38 UTC
    I haven't tried String::Interpolate myself, but I've used Template a fair bit. It might be overkill for what you want to do, but basic usage is a pretty quick study -- e.g.:
    perl -MTemplate -e '$t="Hello [% foo %] world\n"; $T=Template->new(); +$foo="whatever"; $T->process(\$t, {foo=>$foo})'
    If you would like to do things like conditionals and loops within the template, then this is a really nice package.