in reply to Split on field length

The general technique here is @parts = $string =~ /(.{1,44}(?:,|$))/g; You get chunks of up to 45 characters, ending either with a comma or at the end of the string. If there's a possibility of newlines in your data, just add the /s modifier to the regex.

Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

Replies are listed 'Best First'.
Re^2: Split on field length
by goldclaw (Scribe) on Sep 29, 2005 at 12:13 UTC
    Of course, if a name is longer than 45 char's this will silently eat the start of that name. Im not sure if its at all possible to handle this nicely with a regexp, at least I have never managed to do it. Problems is how to handle the case where you cant break the input the way you want.

    Now, it wasn't really specified how to handle this situation, maybe break on whitespace instead? Or just simply overflow? (One application I work with frequently will hang forever trying to break a line longer than 80 characters if there are no spaces in it:-). Anyway, if overflowing is the solution for this particular problem, then Text::Wrap might come to the rescue:

    use Text::Wrap qw(wrap); my @parts=do { local $Text::Wrap::columns=45; local $Text::Wrap::huge='overflow'; local $Text::Wrap::separator=",\n"; local $Text::Wrap::break=qr/\s*,\s*/; split /\n/, wrap('','',$string); };
    gc