我需要插入放在双引号中的字符串变量的值。我使用下面的代码: -
$username="abc";
$password="123";
my $post_data = '{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"$username","password":"$password"} }}';
print $post_data;
它显示的输出如下: -
{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"$username","password":"$password"} }}
但我希望输出如下: -
{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"abc","password":"123}"}}
答案 0 :(得分:4)
只需使用qq
quoting operator显式设置封闭字符串文字的插值行为,如下所示:
my $post_data = qq'{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"$username","password":"$password"} }}';
Demo。请注意,在这里使用单引号作为分隔符实际上不是一个好的选择,因为任何新的开发人员可能会对它感到困惑(期望不会插入字符串)。但是,如文档中所示,您可以将其替换为任何非空白字符(只要它不在字符串中,或者您可以轻松地将其转义)。例如:
my $post_data = qq~{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"$username","password":"$password"} }}~;
尽管如此,最明确的方法是将整个结构编写为HoH文字,然后将其编码为JSON。它看起来类似于:
use JSON;
my $username = 'abc';
my $password = '123';
my $post_data = {
auth => {
tenantName => 'admin',
passwordCredentials => {
username => $username,
password => $password
}
}
};
print to_json($post_data);
现在代码的目标非常明确。 )
答案 1 :(得分:1)
最简单的方法:
my $post_data = sprintf '{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"%s","password":"%s"} }}', $username, $password;
但我建议你使用JSON模块,并用它创建json