Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: How to Split on specific occurrence of a comma

by eyepopslikeamosquito (Bishop)
on Dec 03, 2020 at 23:26 UTC ( #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

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? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2021-07-30 01:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?