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

Monks,

I have a hash of arrays. Each array has been populated with comma-separated values from a regular expression

if ($txtfile =~ m/(some associative pattern for each CSV list)/gs) { my $key = $1; while ($txtfile =~ m/(CSV)/gs) { push @{$hash{$key}}, $1 } }

I would like to split the array values so that each element in each array only contains consecutive values of the CSV.

The code above stores all values as a single element if some condition is met.

In other words, how do I turn this:

@{$hash{$key}}[0] = 0,1,2,3 @{$hash{$key}}[1] = 4,5 @{$hash{$key}}[2] = 6,7,8,9

Into this:

@{$hash{$key}}[0] = 0,1 @{$hash{$key}}[1] = 2,3 @{$hash{$key}}[2] = 4,5 ...

For each referenced array within each key/value pair

Any help would be greatly appreciated

Replies are listed 'Best First'.
Re: Iterating through referenced arrays wihthin a hash
by ikegami (Patriarch) on Jun 03, 2008 at 04:10 UTC
    The whole reference thing is a red heiring. Your question (as I understand it) pretty much boils down to "How do I split a list into pairs?"
    my @vals = map { @$_ } @{ $hash{$key} }; my @pairs; while (@vals) { push @pairs, [ splice(@vals, 0, 2) ]; } $hash{$key} = \@pairs;
Re: Iterating through referenced arrays wihthin a hash
by dragonchild (Archbishop) on Jun 03, 2008 at 13:13 UTC
    Use CPAN. Specifically, the natatime() function in List::MoreUtils.
    my @arr = ( [ 0 .. 3 ], [ 4 .. 5 ], [ 6 .. 9 ], ); my @all = map { @$_ } @arr; my $iterator = natatime @all, 2; @arr = (); while ( my @v = $iterator->() ) { push @arr, \@v; }

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?