使用s /替换另一个变量的变量

时间:2012-05-09 18:00:41

标签: perl

我有以下哈希结构

test =>  '/var/tmp $slot'

my $slot_number = 0;  # just another variable.

然后我获取密钥的值并存储在名为$ test_command

的变量中

现在我需要将$slot中的$test_command替换为另一个名为$slot_number的变量 所以我正在尝试这个

$test_command =~ s/$slot/$slot_number/g;  this does not work

$test_command =~ s/$slot/$slot_number/ee; does not work

$test_command =~ s/\$slot/\$slot_number/g; this does not work

预期输出应为

$test_command = /var/tmp 0

2 个答案:

答案 0 :(得分:3)

这个怎么样? $test_command=~s/\$slot/$slot_number/g;

此代码:

my $slot_number = 5;
my $test_command = '/var/tmp $slot';
$test_command=~s/\$slot/$slot_number/g;
print "$test_command\n";

打印:

/var/tmp 5

如果要将其替换为值,则不希望转义第二个变量。

答案 1 :(得分:1)

你真是太近了!看看以下内容是否符合您的要求:

use strict;
use warnings;

my $test_command = '/var/tmp $slot';
my $slot_number = 0;

$test_command =~ s/\$slot/$slot_number/;

print $test_command;

<强>输出

/var/tmp 0
相关问题