Quick question. I want to iterate over a column in a csv
file that loops like the following:
columnA columnB
123 9
123 8
123 11
543 7
234 10
234 8
How can i loop through this list, and for each number that is the same
in columnA take the number in columnB and them group them together
separated by a pipe. So it eventually would look like this:
123 8|9|11
543 7
234 8|10
Thank you,
how do YOU think you would attack this? Start with the end in mind -
that is, start by thinking about what kind of data structure you would
store your data in. refer to perldsc if necessary. hint: your output
models one particularly common data structure.
this is not a "write a script for me" kind of place. show that you've
made at least some kind of effort, or thought about how you would break
this problem up into digestable chunks.
-jp
What i originally was working on is this following, i just posted a
simpler version of it:
Either way im still stuck: :(
Any Pointers ?
use Tie::Handle::CSV;
$csv_fh = Tie::Handle::CSV->new('csvfile.csv');
$\ = "|";
while(<$csv_fh>){
$StyleField = ( scalar <$csv_fh> )->{'Style'};
$SizeField = ( scalar <$csv_fh> )->{'Size'};
# push @{$hash{$StyleField}}, $SizeField;
}
The output:
123234 8|9|10
234345 7|8.5
The original:
123345 9
123345 8
123345 10
234345 8.5
234345 7
Thanks,
I'm not clear on where you are stuck. At any rate, I wouldn't use the
CSV module... I would approach it with basic Perl as shown here. This
is not the most efficient way to do it if your input data is guaranteed
to be sorted, but it will work for sorted or unsorted data:
#!/usr/bin/perl
use strict;
use warnings;
my %stuff;
while( <DATA> ) {
my ($style, $size) = split;
push @{$stuff{$style}}, $size;
}
foreach my $style( sort keys %stuff ) {
printf "%s %s\n", $style, join( "|", @{$stuff{$style}} );
}
__DATA__
123345 9
123345 8
123345 10
234345 8.5
234345 7
--
David Filmer (http://DavidFilmer.com)