Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change match modifier within a program in perl? [duplicate]

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 517
bem33 Avatar asked Nov 21 '22 14:11

bem33


2 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 164
Eric Strom Avatar answered Apr 12 '23 22:04

Eric Strom


You could use eval, if you put on your safety goggles and your divide-by-zero suit.

E.g.:

use strict;
use warnings;
sub mk_re {
  my ($search, $replace, $modifier) = @_;
  $modifier ||= '';
  die "Bad modifier $modifier" unless $modifier =~ /^[msixge]*$/;
  my $sub = eval "sub { s/($search)/$replace/$modifier; }";
  die "Error making regex for [$search][$replace][$modifier]: $@" unless $sub;
  return $sub;
}

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

# Sub can be stored in an array or hash
my $sub = mk_re($search, $replace, $modifier);

$_ = "abc-looking-def";
print "$_\n";
$sub->();
print "$_\n";
like image 27
mob Avatar answered Apr 12 '23 22:04

mob