Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: How to Split on specific occurrence of a comma

by eyepopslikeamosquito (Archbishop)
on Dec 03, 2020 at 23:26 UTC ( [id://11124614]=note: print w/replies, xml ) Need Help??


in reply to How to Split on specific occurrence of a comma

Your problem reminds of this old node: Rosetta code: Split an array into chunks

Adapting that code to your problem shows how we can employ functions from List::MoreUtils to this problem.

use strict; use warnings; use List::MoreUtils qw(part natatime); use Data::Dumper; # Load test DATA below into an array of teams (adapted from original n +ode) my $line; my @teams; while ( $line = <DATA> ) { chomp $line; if ($line =~ /^#/ || $line =~ /^\s*$/) { next; } $line =~ s/^[^=]*\=//; push @teams, split( /,/, $line ); } print Dumper \@teams; # ------------------------------------------------------ # Adapted from https://perlmonks.org/?node_id=861938 # Using natatime sub chunk_array { my ($n, @vals) = @_; my $str; my $iter = natatime($n, @vals); while ( my @line = $iter->() ) { $str .= join(",", @line) . ",\n"; } $str =~ s/,$//; return $str; } # Using part sub chunk_array_2 { my ($n, @vals) = @_; my $str; my $i = 0; $str = join "", map { join(",", @$_).",\n" } part { $i++/$n } @val +s; $str =~ s/,$//; return $str; } my $v1 = chunk_array(3, @teams); print "Version 1--------------\n"; print $v1; my $v2 = chunk_array_2(3, @teams); print "Version 2--------------\n"; print $v2; #--------------------------------------- __DATA__ Teams=PATRIOTS,BILLS,DOLPHINS,JETS,COWBOYS,GIANTS,EAGLES,REDSKINS,BENG +ALS,OILERS,STEELERS,BROWNS,SEAHAWKS,RAMS,49ERS,RAIDERS

Running the test program above produces:

$VAR1 = [ 'PATRIOTS', 'BILLS', 'DOLPHINS', 'JETS', 'COWBOYS', 'GIANTS', 'EAGLES', 'REDSKINS', 'BENGALS', 'OILERS', 'STEELERS', 'BROWNS', 'SEAHAWKS', 'RAMS', '49ERS', 'RAIDERS' ]; Version 1-------------- PATRIOTS,BILLS,DOLPHINS, JETS,COWBOYS,GIANTS, EAGLES,REDSKINS,BENGALS, OILERS,STEELERS,BROWNS, SEAHAWKS,RAMS,49ERS, RAIDERS Version 2-------------- PATRIOTS,BILLS,DOLPHINS, JETS,COWBOYS,GIANTS, EAGLES,REDSKINS,BENGALS, OILERS,STEELERS,BROWNS, SEAHAWKS,RAMS,49ERS, RAIDERS

References Added Later

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11124614]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2025-07-16 14:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.