How to use a variable as modifier in a substitution

后端 未结 5 930
感情败类
感情败类 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:51

    Here's a combination of Kinopiko's answer and eval.

    eval is used here to generate the lookup table in a controlled and maintainable fashion, and a lookup table is used to save all the if.. elsif.. elsif which are not too fun to look at.

    (very lightly tested)

    my @stuff = (
    {
        search => "this",
        replace => "that",
        modifier => "g",
    },
    {
        search => "ono",
        replace => "wendy",
        modifier => "i",
    }
    );
    $_ = "this ono boo this\n";
    
    my @modifiers = qw{m s i x g e};
    
    my $s_lookup = {};
    
    foreach my $modifier (@modifiers) { 
        $s_lookup->{$modifier} =  eval " sub { s/\$_[0]/\$_[1]/$modifier } ";
    }
    
    for my $h (@stuff) {
        $s_lookup->{$h->{modifier}}->($h->{search},$h->{replace});
    }
    
    print; 
    

    To be fully useful this needs:

    1. combinations of possible modifiers
    2. sort function on the lookup table so 'msi' combination and 'mis' combination will go to the same key.

提交回复
热议问题