Evaluating escape sequences in perl

后端 未结 3 1513
暗喜
暗喜 2020-12-12 03:40

I\'m reading strings from a file. Those strings contain escape sequences which I would like to have evaluated before processing them further. So I do:

$t = e         


        
相关标签:
3条回答
  • 2020-12-12 03:46

    It's not quite clear what the strings in the file look like and what you do to them before passing off to eval. There's something missing in the explanation.

    If you simply want to undo C-style escaping (as also used in Perl), use Encode::Escape:

    use Encode qw(decode);
    use Encode::Escape qw();
    my $string_with_unescaped_literals = decode 'ascii-escape', $string_with_escaped_literals;
    

    If you have placeholders in the file which look like Perl variables that you want to fill with values, then you are abusing eval as a poor man's templating engine. Use a real one that does not have the dangerous side effect of running arbitrary code.

    0 讨论(0)
  • 2020-12-12 03:46
    $string =~ s/\\([rnt'"\\])/"qq|\\$1|"/gee
    

    string eval can solve the problem too, but it brings up a host of security and maintenance issues, like @ in string

    0 讨论(0)
  • 2020-12-12 03:49

    oh gah don't use eval for this, thats dangerous if someone provides it with input like "system('sync;reboot');"..

    But, you could do something like this:

    #!/usr/bin/perl
    
    $string = 'foo\"ba\\\'r';
    printf("%s\n", $string);
    $string =~ s/\\([\"\'])/$1/g;
    printf("%s\n", $string);
    
    0 讨论(0)
提交回复
热议问题