简体   繁体   中英

Whole regexp string as variable

my $re = 's/foo/bar/g';
my $x = 'one two foo';

$x =~ $re;

How to do this?

my $re1 = 'foo';
my $re2 = 'bar';

my $x = 'one two foo';

$x =~ s/$re1/$re2/g;

...is not a solution for me! Many thanks in advance.

You can use substitution inside anonymous function,

my $re = sub { s/foo/bar/g for @_ };

my $x = 'one two foo';
$re->($x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM