0

I would like to understand this expression meaning.

$req_msg =~ s/ \${$toReplace}/$replacements->{$toReplace}/g;

3 Answers 3

4

Prerequisite for this to work are two variables:

  • $toReplace - contains an arbitrary value
  • $replacements - a HASH ref containing, erm, replacements

Given $toReplace contains "foo", the contents of $req_msq are searched for ${foo} (with a leading single space) with every occurence of this being replaced with $replacements->{foo}.

1
  • I think it would be looking for ${foo}, not $foo.
    – Qtax
    Feb 29, 2012 at 8:49
2

$req_msg =~ s/ \${$toReplace}/$replacements->{$toReplace}/g;

s is used for substitution. $content=~ s/old_value/new_value/modifier; (modifier can be i, g, x, along or combination)

Ex:

$content = "Hi I am a coder and I like coding very much!";
$content =~ s/i/eye/i;

now $content will contain "Heye eye am a coders and eye like coding very much"

In the same way ${$toReplace} which simply means a scalar reference is the old value which needs to be replace and $replacements->{$toReplace} means $replacements is a hash reference whose key is $toReplace . It is smiliar to $hash_value = hash_ref->{key};

whereever it finds the value returned by scalar reference , gets replace by hash reference's key with the corresponding value found in $req_msg

But I guess you asked this question because you got blank replacement. That may be due to scalar reference problem.

This code snippet may help in removing your doubt.

#!/usr/bin/perl
use strict;
use warnings;

my $value = "Jassi";
my $scalar_ref = \$value;

print "scalar_ref = $scalar_ref \n and value = $value and ${$scalar_ref}\n";
my %hash = ("Jassi", "aliencoders");
my $hash_ref = \%hash;
my $reg_msg = "Hi this is Jassi";
print "reg_msg = $reg_msg \n";
$reg_msg =~ s/${$scalar_ref}/$hash_ref->{${$scalar_ref}}/;
print "reg_msg after s = $reg_msg\n";

See the second last line!

0
0

It replaces every occurance of the text ${blabla} with whatever is stored in the hash reference $replacements with the key blabla, e.g.:

$replacements = { 'blabla' => 'blubb' };

will make every ${blabla} being replaced by blubb in $req_msg.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.