Great. I thought of the same solution too, but I feared it would be too slow. I was not able to come with a faster one, though:
#!/usr/bin/perl
use warnings;
use strict;
use Test::More;
use Benchmark qw(cmpthese);
my @arr_s = qw/! my name ! is ! Achint ! I need ! help/;
my @arr_ns = qw/ my name ! is ! Achint ! I need ! help/;
sub simple {
my @arr1 = split / *(!) */, join(' ', @_);
shift @arr1 unless length $arr1[0];
return \@arr1;
}
sub complex {
my @arr2;
my $x = 0;
my $step = 1;
for (@_) {
if ('!' eq $_) {
$x += $step;
push @arr2, '!';
} else {
$arr2[$x] .= (defined $arr2[$x] ? ' ' : q()) . $_;
}
$step = 2;
}
return \@arr2;
}
print join ' # ', @{simple(@arr_s)}, "\n";
print join ' | ', @{simple(@arr_ns)}, "\n";
is_deeply([simple(@arr_s )], [complex(@arr_s )]);
is_deeply([simple(@arr_ns)], [complex(@arr_ns)]);
done_testing();
cmpthese(-5,
{ simple => sub { simple(@arr_s); simple(@arr_ns) },
complex => sub { complex(@arr_s); complex(@arr_ns) },
});
Results on my netbook:
Rate complex simple
complex 10723/s -- -5%
simple 11262/s 5% --