Embedding evaluations in Perl regex

前端 未结 6 1839
猫巷女王i
猫巷女王i 2021-01-05 00:05

So i\'m writing a quick perl script that cleans up some HTML code and runs it through a html -> pdf program. I want to lose as little information as possible, so I\'d like t

6条回答
  •  时光说笑
    2021-01-05 00:43

    The syntax you are using to embed code is only valid in the "match" portion of the substitution (the left hand side). To embed code in the right hand side (which is a normal Perl double quoted string), you can do this:

    $file =~ s{}
              {}gis;
    

    This uses the Perl idiom of "some string @{[ embedded_perl_code() ]} more string".

    But if you are working with a very complex statement, it may be easier to put the substitution into "eval" mode, where it treats the replacement string as Perl code:

    $file =~ s{}
              {'}}gise;
    

    Note that in both examples the regex is structured as s{}{}. This not only eliminates the need to escape the slashes, but also allows you to spread the expression over multiple lines for readability.

提交回复
热议问题