Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

For Loop Through Column

0 views
Skip to first unread message

onlineviewer

unread,
Jul 23, 2006, 4:51:57 PM7/23/06
to
Hello All,

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,

DJ Stunks

unread,
Jul 23, 2006, 6:50:10 PM7/23/06
to

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

Message has been deleted
Message has been deleted

onlineviewer

unread,
Jul 23, 2006, 10:55:15 PM7/23/06
to
Hi,

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,

use...@davidfilmer.com

unread,
Jul 28, 2006, 4:12:46 PM7/28/06
to
onlineviewer wrote:
> Either way im still stuck: :(
> Any Pointers ?

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)

0 new messages