halfcountplus has asked for the wisdom of the Perl Monks concerning the following question:

looking at regexp s/mode quicktest i'd like to add a "suffix: " to the test. Is there a way to do this:
($output = $string) =~ s/$regexp/$new/$suffix;
seems impossible because $suffix is Scalar found where operator expected

Replies are listed 'Best First'.
Re: unconventional string substitutions
by ikegami (Patriarch) on Mar 20, 2008 at 03:23 UTC
Re: unconventional string substitutions
by hipowls (Curate) on Mar 20, 2008 at 07:08 UTC

    Another approach is to use embedded flags, it is possible to embed all the modifiers except /g and /c

    #!/net/perl/5.10.0/bin/perl use strict; use warnings; use 5.010_000; my $string = 'This is perl, the Perl interpreter'; foreach my $flag ( '', 'i' ) { if ( my ($match) = $string =~ /(?$flag:(Perl))/ ) { print "$match\n"; } } Perl perl __END__

    Update: also doesn't work with /c, add it above.

Re: unconventional string substitutions
by tachyon-II (Chaplain) on Mar 20, 2008 at 03:29 UTC

    Have a look at eval. Something like this (untested) should work as you desire. I don't think you need the block eval but do not have the ability to test. eval has security implications.

    eval{ eval "(\$output = \$string) =~ s/\$regexp/\$new/$suffix" };

      The outer eval is indeed not needed. Both forms of eval catch exceptions.

      As long as $suffix is constrained to /^[xismg]+\z/, there should be no security issues from the eval. There are, however, security issues with regexes, though. The following should be a good *start*:

      my $string = ...; my $regexp = ...; my $new = ...; my $suffix = ...; my $timeout = 2; my $output; $suffix =~ /^[xismg]+\z/ or die("Bad suffix\n"); my $sop = eval "sub { s/\$regexp/\$new/$suffix }"; or die("Bad regexp: $@\n"); eval { local $SIG{ALRM} = sub { die "Alarm\n" }; alarm($timeout); $sop->() for $output = $string; 1 } or die("Timeout\n");

      The denial of service isn't completely addressed. Even though the search is limited to $timeout seconds, the user can send requests faster than once a second.

      The security risk from bugs in the regexp engine isn't addressed at all.