如何在 Perl 中插入非内插字符串
How to make a non-interpolate string interpolate in Perl
一旦确定其中包含“$”,如何对下面的字符串进行插值?
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";
我得到:
He is $yrs years old.
我想得到:
He is 4 years old.
您正在尝试编写模板系统。周围有很多这样的东西,所以你不必费心自己写。
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;
我可能会用 sprintf
:
来写
my $template = 'He is %d years old.';
my $output = sprintf $template, $years;
一旦确定其中包含“$”,如何对下面的字符串进行插值?
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";
我得到:
He is $yrs years old.
我想得到:
He is 4 years old.
您正在尝试编写模板系统。周围有很多这样的东西,所以你不必费心自己写。
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;
我可能会用 sprintf
:
my $template = 'He is %d years old.';
my $output = sprintf $template, $years;