I'm writing code to divide up (big) text strings "from the back" in perl (i.e. end-to-start or right-to-left) into equal-size chunks (with remainder at the front).
It's working, but this seems to be a case where perl's "it's easy/fast to do (conceptually) easy things" paradigm is breaking down.
The most elegant way I found is adapted from here: How do I display large numbers with commas? HTML
my @a = split /(?=(?:.{8})+$)/,$a;
But this is very slow as the strings get very large, probably due to all the necessary backtracking. Is there maybe a more efficient way using the same idea (or any regexp)?
I rejected the idea of "reverse input, process forward, reverse output" out-of-hand out of similar inefficiency concerns. But I'd welcome correction on those concerns if anyone knows anything about that.
I did do a brute-force "iteration of substr's" implementation, which was fine but inelegant.
Only slightly less elegant but also slightly faster is an implementation using unpack
I've currently got running, as adapted from here: Split a String into Equal Length Chunk in Perl
use integer;
my $la = length($a);
my $r = $la % 8;
my @a = unpack(($r?"a$r":"")."(a8)"x($la/8), $a);
Pretty ugly. Even the seeming simplification "(a8)*"
(instead of the x
) fails because for some reason perl gives an extra ""
at the end in cases where length is less than 8, say 5, and the unpack template is "a5(a8)*"
. (Anybody have an explanation for that "feature"? :-S)
Any better ideas for simplification without introducing inefficiency? Thanks.