How to use a variable as modifier in a substitution

后端 未结 5 924
感情败类
感情败类 2020-12-07 02:06

Is there a way to use a variable as modifier in a substitution?

my $search = \'looking\';
my $replace = \'\"find: $1 =\"\';
my $modifier = \'ee\';

s/$search         


        
5条回答
  •  离开以前
    2020-12-07 02:49

    While the method using eval to compile a new substitution is probably the most straightforward, you can create a substitution that is more modular:

    use warnings;
    use strict;
    
    sub subst {
        my ($search, $replace, $mod) = @_;
    
        if (my $eval = $mod =~ s/e//g) {
            $replace = qq{'$replace'};
            $replace = "eval($replace)" for 1 .. $eval;
        } else {
            $replace = qq{"$replace"};
        }
        sub {s/(?$mod)$search/$replace/ee}
    }
    
    my $sub = subst '(abc)', 'uc $1', 'ise';
    
    local $_ = "my Abc string";
    
    $sub->();
    
    print "$_\n";  # prints "my ABC string"
    

    This is only lightly tested, and it is left as an exercise for the reader to implement other flags like g

提交回复
热议问题