in reply to perl: How to comapre and manipulate csv file in perl?
Your script is hard to read indeed. Not just because you got confused on how to do the work, but also because of bad names. First, if your variables are numbered (like @row1, @row2), there's a high chance that it would be a good idea to put them in an array, or change their name. In your case, @previousRow and @currentRow would have been far more explicit. I have no idea what $flag and $flag1 are used for, but I'm sure they could have better names. And BTW, you should avoid $flag++ if the only values $flag can take are 0 or 1. Write $flag = 1; instead.
Now, for your issue, there is an association that is often useful in perl: unique means hash. If you want only one record for each unique amount, amountId and MRP combinaison, put them in a hash as keys, and the rest of the values in the associated value.
perldata and perldsc could be a good read.# I didn't copy the top of your file, and you should add use Data::Dum +per; if you want this code to work my $header = $csv->getline($FH); my @keys = @$header; my %result; while (my $row = $csv->getline($FH)) { my %currentRow; @currentRow{@keys} = @$row; print "Current row: ", Dumper \%currentRow; my $uniqueKey = "$currentRow{Amount} & $currentRow{AmountId} & $curr +entRow{MRP}"; # Bad idea if '&' is allowed in either of those values if(!exists $result{$uniqueKey}) # If this combinaison is unknown { $result{$uniqueKey} = [\%currentRow]; # save the current row to it } else { push @{ $result{$uniqueKey} }, \%currentRow; # add the current row + to the ones with the same ID } } print "Result: ", Dumper \%result;
Edit: or the short version following AnomalousMonk's post:
while (my $row = $csv->getline($FH)) { my %currentRow; @currentRow{@keys} = @$row; print "Current row: ", Dumper \%currentRow; my $uniqueKey = "$currentRow{Amount} & $currentRow{AmountId} & $curr +entRow{MRP}"; # Bad idea if '&' is allowed in either of those values push @{ $result{$uniqueKey} }, \%currentRow; # add the current row t +o the existing ones } print "Result: ", Dumper \%result;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: perl: How to comapre and manipulate csv file in perl?
by AnomalousMonk (Archbishop) on Oct 01, 2014 at 16:34 UTC | |
by Eily (Monsignor) on Oct 01, 2014 at 16:45 UTC |