0

在 perl 脚本中,我想在字符串变量中评估内存组特殊变量:

my $string="3-4";
my $cal='first is $1;second is $2';
my $regex='^(.)-(.)$';

if($string=~ $regex){
    print $cal;
        #print "first is $1;second is $2";
}

我想打印:“第一个是 3;第二个是 4”(就像第二个打印一样)。

在我的示例中,只有 2 个特殊变量,但特殊字符的数量无法提前确定,因为$cal它们$regex存储在数据库中。

如何评估字符串$cal(如 php 中的 eval )?

4

2 回答 2

1

听起来您想定义一个模式,您的匹配项将被插入其中?您可以为此使用printf,例如

my $string="3-4";
my $cal="%s %s\n";
if($string=~ '^(.)-(.)$'){
    printf($cal, $1, $2);
}

如果您只是想将所有匹配项连接在一起,并且您不知道可能有多少匹配项,请尝试这样的操作

my @matches=$string=~ '^(.)-(.)$';
if (scalar(@matches))
{
    print join(' ',@matches);
}
于 2012-03-27T23:13:11.593 回答
0
print eval "\"$cal\"","\n";

外部 dblquotes 用于 eval "",内部转义引号用于内部插值print "$1 $2","\n";

或者,您可以像这样组合打印段print eval "\"$cal\n\"";

于 2012-03-27T23:45:22.953 回答