Reputation: 960
How can I make the string below interpolate once it's determined that it has a '$' in it?
use strict;
my $yrs;
my $stg = 'He is $yrs years old.';
if ($stg =~ /[@#\$\%\/]/) {
print "Matched dollar sign.\n";
$yrs = '4';
} else {
print "No Match.\n";
}
print "Year's scalar: $yrs\n";
print $stg . "\n";
I get:
He is $yrs years old.
I would like to get:
He is 4 years old.
Upvotes: 3
Views: 125
Reputation: 132802
I'd probably write that with sprintf
:
my $template = 'He is %d years old.';
my $output = sprintf $template, $years;
Upvotes: 1
Reputation: 385764
You are trying to write a template system. There are plenty of those around, so you don't have to go to through the trouble of writing your own.
use Template qw( );
my $template = 'He is [% years %] years old.';
my $vars = {
years => 4,
};
my $tt = Template->new();
$tt->process(\$template, $vars, \my $output)
or die($tt->error());
say $output;
Upvotes: 6