Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable as modifier in a substitution

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/$replace/$modifier;

I need to use an array of hashes to make bulk search-replace with different modifiers.

like image 903
bem33 Avatar asked Jul 13 '10 14:07

bem33


People also ask

How does variable substitution work?

The method of solving "by substitution" works by solving one of the equations (you choose which one) for one of the variables (you choose which one), and then plugging this back into the other equation, "substituting" for the chosen variable and solving for the other. Then you back-solve for the first variable.

What are variable modifiers?

The variables used for personalization can be altered with modifiers. A modifier is called on the variable by appending it with a | before the closing curly brace. E.g. if you want to apply the tolower modifier on variable {$name} you use: {$name|tolower} .


1 Answers

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

like image 102
Eric Strom Avatar answered Sep 28 '22 06:09

Eric Strom