How can I interpolate the literal \ t and \ n in Perl strings?

Say I have myvar environment myvar :

 myvar=\tapple\n 

When the following command prints this variable

 perl -e 'print "$ENV{myvar}"' 

I will literally have \tapple\n , however, I want these control characters to be evaluated and not escaped. How can i achieve this?

In the real world, $ENV is in substitution, but I hope the answer will cover it.

+4
source share
3 answers

Use eval :

 perl -e 'print eval qq{"$ENV{myvar}"}' 

UPD: you can also use replacement with the ee switch, which is safer:

 perl -e '(my $s = $ENV{myvar}) =~ s/(\\n|\\t)/"qq{$1}"/gee; print $s' 
+3
source

You should probably use String::Escape .

 use String::Escape qw(unbackslash); my $var = unbackslash($ENV{'myvar'}); 

unbackslash unescapes any escape sequences that it finds, turning them into the characters they represent. If you want to explicitly translate only \n and \t , you probably have to do it yourself with s ubstitution, as in this answer .

+2
source

There is nothing special about a character sequence that includes \ . If you want to replace one sequence of characters with another, this is very easy to do in Perl:

 my %sequences = ( '\\t' => "\t", '\\n' => "\n", 'foo' => 'bar', ); my $string = '\\tstring fool string\\tfoo\\n'; print "Before: [$string]\n"; $string =~ s/\Q$_/$sequences{$_}/g for ( keys %sequences ); print "After: [$string]\n"; 

The only trick with \ is to keep track of when Perl considers it an escape character.

 Before: [\tstring fool string\tfoo\n] After: [ string barl string bar ] 

However, as darch notes , you can just use String :: Escape .

Note that you must be very careful when accepting values โ€‹โ€‹from environment variables. I would not want to use String::Escape , since it could handle a little more than you are ready to translate. The safe way is to only expand on the specific values โ€‹โ€‹that you explicitly want to allow. See the โ€œSafe Programming Techniquesโ€ chapter in Mastering Perl for a discussion of this, along with a taint test that you might want to use in this case.

+1
source

Source: https://habr.com/ru/post/1309788/


All Articles