How to use a variable as modifier in a substitution

后端 未结 5 928
感情败类
感情败类 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 03:09

    Hm, if I had to do it I would do like this:

    use warnings;
    use strict;
    my @stuff = (
    {
        search => "this",
        replace => "that",
        modifier => "g",
    },
    {
        search => "ono",
        replace => "wendy",
        modifier => "i",
    }
    );
    $_ = "this ono boo this\n";
    for my $h (@stuff) {
        if ($h->{modifier} eq 'g') {
            s/$h->{search}/$h->{replace}/g;
        } elsif ($h->{modifier} eq 'i') {
            s/$h->{search}/$h->{replace}/i;
        }
        # etc.
    }
    print;
    

    There are only so many different modifiers you might want to use so I think this is easy enough.

    You can use eval for this, but it's awfully messy.

提交回复
热议问题