How can I manually interpolate string escape strings in a Perl string?

In perl, suppose I have a type string 'hello\tworld\n', and I want:

'hello  world
'

That is, “hello,” then the literal tab character, then “peace,” and then the literal line of the new line. Or, which is the same thing "hello\tworld\n"(note the double quotes).

In other words, is there a function for taking a string with escape sequences and returning an equivalent string with all interpolating escape sequences? I don't want to interpolate variables or anything else, just avoid sequences like \xwhere where xis the letter.

+5
source share
2 answers

It seems like a problem that someone else has solved already . I have never used this module, but it looks useful:

use String::Escape qw(unbackslash);
my $s = unbackslash('hello\tworld\n');
+8
source

You can do this with "eval":

my $string = 'hello\tworld\n';
my $decoded_string = eval "\"$string\"";

Note that there are security issues associated with this approach if you do not have 100% control of the input string.

Edit: if you want ONLY to interpolate \ x substitutions (and not the general case of “something that Perl will interpolate in the quoted string”), you can do this:

my $string = 'hello\tworld\n';
$string =~ s#([^\\A-Za-z_0-9])#\\$1#gs;
my $decoded_string = eval "\"$string\"";

This does almost the same thing as quotemeta, but frees the '\' characters from escaping.

Edit2: this is still not 100% safe, because if the last character is "\" - it "seeps" beyond the end of the line, though ...

, 100% , , , eval:

my %sub_strings = (
    '\n' => "\n",
    '\t' => "\t",
    '\r' => "\r",
);

$string =~ s/(\\n|\\t|\\n)/$sub_strings{$1}/gs;
+2

All Articles