Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I would like to split a string into four semi-equal parts but the string can only be split on a comma.
$string = "TE=ASR,EV=R,PPF=G1,TG=G1,TMT=P1,RTV=YE,AAT=0,AT=105,ON=Y,CF +1=FGOC";
Desired Output:
TE=ASR,EV=R,PPF=G1 TG=G1,TMT=P1,RTV=YE AAT=0,AT=105 ON=Y,CF1=FGOC
The string could have up to 40 fields.

Replies are listed 'Best First'.
Re: split a string into four parts on comma
by ikegami (Patriarch) on Oct 25, 2006 at 02:27 UTC
    my $string = "TE=ASR,EV=R,PPF=G1,TG=G1,TMT=P1,RTV=YE,AAT=0,AT=105,ON=Y +,CF1=FGOC"; my @fields = split /,/, $string; my $per_group = int(@fields / 4); my $extras = @fields - $per_group*4; while (@fields) { my $n = $per_group; if ($extras) { $extras--; $n++; } print(join(',', splice(@fields, 0, $n)), "\n"); }
Re: split a string into four parts on comma
by GrandFather (Saint) on Oct 25, 2006 at 02:50 UTC

    using a regex:

    use warnings; use strict; my $string = "TE=ASR,EV=R,PPF=G1,TG=G1,TMT=P1,RTV=YE,AAT=0,AT=105,ON=Y +,CF1=FGOC"; my $width = int (length ($string) * 0.28); my @parts = $string =~ m/(.{1,$width},)(.{1,$width},)(.{1,$width},)(.* +)/; print join "\n", @parts;

    Prints:

    TE=ASR,EV=R,PPF=G1, TG=G1,TMT=P1, RTV=YE,AAT=0, AT=105,ON=Y,CF1=FGOC

    DWIM is Perl's answer to Gödel
Re: split a string into four parts on comma
by driver8 (Scribe) on Oct 25, 2006 at 02:29 UTC

    There would be many ways to do this, ranging from kind of tricky to very complicated. Have you even taken a stab at this yourself, or do you just want us to write your code for you?

    Edit: nevermind, ikegami just wrote your code for you :)

    -driver8
      This is the best I did...
      my $string = "TE=ASR,EV=R,PPF=G1,TG=G1,TMT=P1,RTV=YE,AAT=0,AT=105,ON=Y +,CF1=FGOC"; my @system_options = split /,/, $string; print @system_options[0 .. 9], "\n"; print @system_options[10 .. 19], "\n"; print @system_options[20 .. 29], "\n"; print @system_options[30 .. 39], "\n";
      It only works if you know the number of items in the array.
      I made many attemps but the results were soooo far off, I decided not to post them.