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");