Search code examples
regexperlsubstitution

How to use an expression in the replacement side of the perl substitution operator?


I'm pretty new to perl and facing one issue. This might sound as a silly question but I want to understand it well.

So I've a string variable containing a substring which I want to replace with a string of hashes.

my $l_filedata = 'abcOVERRIDE_CONTAINS_FUNCTIONSasdfghjk';

and

my $hash_ref = {};
Dumper($hash_ref->{'ContainsMessage'}); # This returns a hash and I've maintained it under scalar variable

Output
------
{
  '23.2.10103' => 1,
  '23.2.10101' => 1,
  '23.2.10102' => 1
}

So I want to perform a find-replace operation and the way I'm doing it is

$l_filedata =~ s/OVERRIDE_CONTAINS_FUNCTIONS/eval(Dumper($hash_ref->{'ContainsMessage'}))/g;

I'm trying to convert the hash to a string using Dumper and then want to replace the string with that Dumper-returned string. But it's always returning me abceval(Dumper(HASH(0xe88f00)))asdfghjk. I think the replacement expression is getting treated as string not an expression.

When I do it like this -

my $temp = Dumper($hash_ref->{'ContainsMessage'});
$l_filedata =~ s/OVERRIDE_CONTAINS_FUNCTIONS/$temp/g;

It's working as expected. Can someone tell me what am I missing here?


Solution

  • Use the e flag to treat the replacement part as code to evaluate rather than the body of string literal.

    s/OVERRIDE_CONTAINS_FUNCTIONS/ Dumper( $hash_ref->{ ContainsMessage } ) /eg
    

    But do you really want to dump the structure multiple times? The following (which you already mentioned) is probably the way to go:

    my $replacement = Dumper( $hash_ref->{ ContainsMessage } );
    
    s/OVERRIDE_CONTAINS_FUNCTIONS/$replacement/g
    

    s{...}{...}
    

    is equivalent to

    s{...}{ qq{...} }e
    

    This means that

    s{...}{eval(Dumper(...))}
    

    is equivalent to

    s{...}{ qq{eval(Dumper(...))} }e
    

    But you simply want

    s{...}{ Dumper(...) }e