Perl Regex 'e' (eval) modifier with s///

后端 未结 3 556
眼角桃花
眼角桃花 2020-12-02 20:37

I\'m having a little trouble comprehending this simple use of the /e regex modifier.

my $var = \'testing\';
$_ = \'In this string we are $var the \"e\" modif         


        
3条回答
  •  天命终不由人
    2020-12-02 21:10

    To be clear, the s//ee form is not modifying your regex pattern or regex interpretation at all. It is an optional treatment of the replacement side string after the regex is performed. (See PERLOP Regex Quote-like operators)

    The e or ee just get mixed into the PATTERN side regex options in the s/PATTERN/REPLACEMENT/msixpodualgcer form.

    From Perlop:

    Options are as with m// with the addition of the following replacement specific options:

    e Evaluate the right side as an expression.
    ee  Evaluate the right side as a string then eval the result.
    r   Return substitution and leave the original string untouched.
    

    You can see the same e vs ee type behavior in non regex situations, as this example shows:

    #!/usr/bin/perl 
    use warnings;
    use strict;
    
    my $var = "var's contents";
    my $str='"-> $var <-"';
    print eval('$str'), "\n";        # equivalent to s//e
    print eval(eval('$str')), "\n";  # equivalent to s//ee
    

    Output:

    "-> $var <-"
    -> var's contents <-
    

提交回复
热议问题