Reputation: 109
I need to insert values of string variables placed in double quotes. I am using below code :-
$username="abc";
$password="123";
my $post_data = '{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"$username","password":"$password"} }}';
print $post_data;
It is showing output like :-
{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"$username","password":"$password"} }}
But i want output like :-
{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"abc","password":"123}"}}
Upvotes: 2
Views: 119
Reputation: 106385
Just use qq
quoting operator to explicitly set the interpolating behavior for an enclosed string literal, like this:
my $post_data = qq'{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"$username","password":"$password"} }}';
Demo. Note that using single-quote as a delimiter here is actually not a good choice, as any new developer might get confused with it (expecting that string won't be interpolated). But, as shown in the doc, you can swap it for any non-whitespace character (as long as it's not in the string OR you can easily escape it there). For example:
my $post_data = qq~{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"$username","password":"$password"} }}~;
Still, the clearest approach would be writing the whole structure as a HoH literal, then encoding it into JSON. It'll look similar to:
use JSON;
my $username = 'abc';
my $password = '123';
my $post_data = {
auth => {
tenantName => 'admin',
passwordCredentials => {
username => $username,
password => $password
}
}
};
print to_json($post_data);
Now the goal of the code is crystal clear. )
Upvotes: 4
Reputation: 4243
Simplest way:
my $post_data = sprintf '{ "auth": {"tenantName":"admin", "passwordCredentials": {"username":"%s","password":"%s"} }}', $username, $password;
But i suggest you to use JSON module, and create json with it
Upvotes: 1