Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I manually interpolate string escapes in a Perl string?

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

'hello  world
'

That is, "hello", then a literal tab character, then "world", then a literal newline. Or equivalently, "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 the escape sequences interpolated? I don't want to interpolate variables or anything else, just escape sequences like \x, where x is a letter.

like image 954
Ryan C. Thompson Avatar asked Apr 17 '10 21:04

Ryan C. Thompson


People also ask

How do I escape a string in Perl?

The backslash is the escape character and is used to make use of escape sequences. When there is a need to insert the escape character in an interpolated string, the same backslash is used, to escape the substitution of escape character with ” (blank). This allows the use of escape character in the interpolated string.

How do I escape a quote in Perl?

Escaping the escape character If you put a back-slash \ in a double-quoted string, Perl will think you want to escape the next character and do its magic.

Does Perl allow variable interpolation?

Perl interpolates variables in double-quoted strings. It means if you place a variable inside a double-quoted string, you'll get the value of the variable instead of its name. Perl interpolates the value of $amount into the string which is 20. Note that Perl only interpolates scalar variables and arrays, not hashes.

What is Perl interpolation?

Interpolation in Perl refers to the process where the respective values replace the variable names. It is commonly used inside double-quoted strings.


1 Answers

Sounds like a problem that someone else would have solved already. I've never used the module, but it looks useful:

use String::Escape qw(unbackslash);
my $s = unbackslash('hello\tworld\n');
like image 168
FMc Avatar answered Nov 14 '22 23:11

FMc