You missed the corrections some have added. There is still the extra space at the end in certain cases. See oshalla's post and my update above.
I added my second code snippet and ran this:
#!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); my $x = "0123456789abcdefg" x 6000 . "XXX"; sub subst { my $s = $x; $s =~ s/(.{16})/$1 /sg; $s }; sub up { join ' ', unpack '(A16)*', $x }; sub re { join ' ', $x=~ /(.{1,16})/g }; sub m_substr { my $s = $x; for (my $i=16*int((length($s)-1)/16);$i;$i-=16) { substr($s,$i,0)=" "; } $s; } sub readline { local $/ = \16; my $s; open my $handle, '<', \$x; $s = <$handle>; while (<$handle>) { $s .= ' ' . $_; } $s; } my $ref = subst(); sub wrap { my ($impl, $sub) = @_; die "Wrong result for $impl!" unless $sub->() eq $ref; } cmpthese(-1, { subst => wrap('subst', \&subst), re => wrap('re', \&re), unpack => wrap('unpack',\&up), substr => wrap('substr',\&m_substr), readl => wrap('readline', \&readline), })
Rate unpack substr subst re readl unpack 29656695/s -- -5% -8% -14% -16% substr 31367657/s 6% -- -3% -9% -11% subst 32410531/s 9% 3% -- -6% -8% re 34622792/s 17% 10% 7% -- -2% readl 35251272/s 19% 12% 9% 2% --
In reply to Re^3: How to split a string into chunks of length n or less
by Skeeve
in thread How to split a string into chunks of length n or less
by isync
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |