in reply to How to split a string into chunks of length n or less
Yesterday I had to learn that string operations might be more efficient. So here we go:
my $x = "0123456789abcdef" x 4 . "XXX"; my $chunksize= 16; for (my $i=$chunksize*int((length($x)-1)/$chunksize);$i;$i-=$chunksize +) { substr($x,$i,0)=" "; }; print $x;
And if you really want to use split Or you might still want a regular expression:
join " ",$x=~/(.{1,$chunksize})/g
Update to my first codesnippet: Thanks to oshalla's comment above I noticed that I also had a space too much when the string has a length being a multiple of chunksize.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to split a string into chunks of length n or less
by moritz (Cardinal) on Aug 21, 2008 at 17:04 UTC | |
by Skeeve (Parson) on Aug 21, 2008 at 17:09 UTC |