in reply to Split a string into items of constant length

One way...

my $string = "a(b)cd(e)f"; my @parts = split /(?=.{5}$)/, $string';
And if your strings are longer and you want to chop it all up the same way...
my $string = "a(b)cd(e)fg(h)ij(k)l"; my @parts = split /(?=(?:.{5})+$)/, $string';
It would be simpler to drop split in this case though...
my $string = "a(b)cd(e)fg(h)ij(k)l"; my @parts = $string =~ /(.{5})/g;

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re^2: Split a string into items of constant length
by blazar (Canon) on Oct 04, 2005 at 10:29 UTC
    my $string = "a(b)cd(e)f"; my @parts = split /(?=.{5}$)/, $string';
    Why using an extended regex to use split where a simple match would do?
    local $_ = "a(b)cd(e)f"; my @parts = split /.{5}/g;
    local $_ = "a(b)cd(e)f"; my @parts = /.{5}/g;
    (Yes: of course this does not take care of the case when the given string has a length that is not a multiple of 5. But then I'm using unpack, as well as Perl Mouse does!)

    Update: fixed a split that I had inadvertently left in -- see stroken out code above. Thanks to sauog's comment.

      Yes: of course this does not take care of the case when the given string has a length that is not a multiple of 5.
      If you want to catch that, you can change the regex to /.{1,5}/g.
      perl -le 'print for "ABCDEFGHIJKLMNOPQRSTUVWXYZ" =~ /.{1,5}/g' ABCDE FGHIJ KLMNO PQRST UVWXY Z
      Of course, depending on what it's used for, simply discarding it can be a better idea, and /.{5}/g works just fine for that.
      my @parts = split /.{5}/g;

      You probably meant to leave split out of that. I'm not sure because of your comment about a string with a length that isn't a multiple of 5 though... In any case, you were probably adding this at the same time I was adding (the correct version of) it as an afterthought to my own post. That's pretty quick as I added it within seconds... :-P

      -sauoq
      "My two cents aren't worth a dime.";