faqts : Computers : Programming : Languages : Perl : Common Problems : Splitting Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

19 of 23 people (83%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I use perl to split a string into equal size pieces?
How can I break up a string into equal pieces placed in an array?

May 16th, 2000 12:44
Nathan Wallace, Per M Knutsen, Tad McClellan, Craig Berry


There are a few ways.  All of these assume a size of 10 and that the
last piece is preserved, even if it is less than the size of the other
pieces.
You can make use of split() returning separators when in parens
in the regex, then using grep() to eliminate the empty strings:
Probably the simplest to express (though also probably not
the most efficient) would be:
  @pieces = $string =~ m/(.{1,10})/gs;
Code snippets for other methods are:
--------------------------------
#!/usr/bin/perl -w
use strict;
$_ = '0123456789abcdefghij0123456789ABCDEFGHIJ0123456789abc';
foreach ( grep length, split /(.{1,10})/  ) {
   print "$_\n";
}
--------------------------------
or, just do it with a m//g:
-------------------------------
#!/usr/bin/perl -w
use strict;
$_ = '0123456789abcdefghij0123456789ABCDEFGHIJ0123456789abc';
my @ra = /(.{1,10})/g;
foreach (  @ra  ) {
   print "'$_'\n";
}
-------------------------------