in reply to Re: Split a string into items of constant length
in thread Split a string into items of constant length

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.

Replies are listed 'Best First'.
Re^3: Split a string into items of constant length
by truedfx (Monk) on Oct 04, 2005 at 13:40 UTC
    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.
Re^3: Split a string into items of constant length
by sauoq (Abbot) on Oct 04, 2005 at 10:47 UTC
    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.";