#!/usr/bin/perl use warnings; use strict; use Test::More; use Benchmark qw{ cmpthese }; sub regex { my ($string, $find, $replace) = @_; $string =~ s/\Q$find/$replace/g; $string } sub substring { my ($string, $find, $replace) = @_; my $length = length $find; my $pos = 0; while (-1 != ( $pos = index $string, $find, $pos )) { substr $string, $pos, $length, $replace; } $string } sub array { my ($string, $find, $replace) = @_; join $replace, split /\Q$find/, $string, -1 } my @args = ('12a345a678a90', 'a', '||'); is regex(@args), '12||345||678||90', 'manual'; for my $args (\@args, [ '123456789abcdefghijkl' x 1000, '123456789abcdefghijkl' x 21, 'ABCDEFGH' ]) { is regex(@$args), substring(@$args), 'regex - substring'; is substring(@$args), array(@$args), 'substring - array'; cmpthese(-3, { regex => sub { regex(@$args) }, substring => sub { substring(@$args) }, array => sub { array(@$args) }, }); } done_testing(5);