my $var = "junk sit here. fkuc lkasjdfie.";
while ($var =~ /(.)/sg) {
my $char = $1;
}
or
for my $i (1 .. length $var) {
my $char = substr($var, $i-1, 1);
}
and when scanning, the method substrworks better than while,
use Benchmark qw( cmpthese ) ;
my $var = "junk sit here. fkuc lkasjdfie." x1000;
cmpthese( -5, {
"while" => sub{
while ($var =~ /(.)/sg) {
my $char = $1;
}
},
"substr" => sub{
for my $i (1 .. length $var) {
my $char = substr($var, $i-1, 1);
}
},
});
result
Rate while substr
while 56.3/s -- -53%
substr 121/s 114% --
source
share