Alex
Alex

Reputation: 897

How can I escaped regular expression metacharacters from an interpolated variable in Perl?

I need to create an "obscuring" function which replaces a clear-text password in line, before writing it to a log.

It looks like this:

function pass_obscure {
      my $logline = shift;
      my $pass = "wer32pass$";   # This password is an example. The real one is received as a parameter, or already stored as a global value.

      $logline =~ s/$pass/*********/g;

      return $logline;
}

But this, of course, doesn't work. The '$' sign in the password string is interpolated as an endline character, so there's no match, and so replacement doesn't work.

How can I resolve this?

Upvotes: 1

Views: 266

Answers (3)

Alex
Alex

Reputation: 897

The solution, of course, is to use:

  my $pattern = quotemeta $pass;
  $logline =~ s/$pattern/********/g;

Upvotes: 0

ephemient
ephemient

Reputation: 205034

In interpolated strings,

\Qquotemeta
\Llc
\llcfirst
\Uuc
\uucfirst
\E → end of the case/quote modifier

Thus this is also a solution.

$logline =~ s/\Q$pass/********/g;

Upvotes: 2

MikeyB
MikeyB

Reputation: 3360

(Why not just keep the password out of the log line in the first place?)

Use quotemeta:

$pass = "password\$";
$logline = "password is: password\$";

print "$pass\n";
print "$logline\n";
$pass_quoted = quotemeta($pass);

$logline =~ s/$pass_quoted/********/g;

print "$logline\n";

Outputs:

password$
password is: password$
password is: ********

Upvotes: 7

Related Questions