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

I am trying to print out the highest value in a given column under a certain condition that it must observe from an adjacent column. I have tried using Spreadsheet::WriteExcel in unison with Spreadsheet::ParseExcel to achieve this but I find it difficult to bring in a condition loop in a generic manner. Any suggestions would be appreciated.

Replies are listed 'Best First'.
Re: Excel and Perl
by wind (Priest) on Jun 08, 2011 at 02:14 UTC

    Spreadsheet::ParseExcel should be all that you'd need.

    Where is the code that you've tried thus far? Where are you actually having trouble?

      #!/usr/bin/perl -w use strict; use Spreadsheet::ParseExcel; use List::Util qw(max); my $parser = Spreadsheet::ParseExcel->new(); my $workbook = $parser->parse('4_19_10_Zrc01a-2.xls'); if ( !defined $workbook ) { die $parser->error(), ".\n"; } for my $worksheet ( $workbook->worksheets() ) { my ( $row_min, $row_max ) = $worksheet->row_range(); my ( $col_min, $col_max ) = $worksheet->col_range(); for my $row ( $row_min .. $row_max ) { for my $col ( $col_min .. $col_max ) { my $cell = $worksheet->get_cell( $row, $col ); next unless $cell; my $i=1; for ($col==5 and $cell->value()==$i){ if ($col==8){ print $cell->value(); print "\n"; }else { $i++; } } } } print "\n"; }
      My sheets contain values in the manner of:
      A B 1 3 1 2 1 4 2 5 2 7 3 10 3 0 3 3 . . 90 90
      I need to find the maximum value in column B for every corresponding value of column A. For example: The maximum value for 1 in col A is 4 in col B. My experience in perl is less than 48 hours, any help will be appreciated. Thank you.

        Just put your data into a hash of arrays, and then loop on the compiled data using List::Util->max to determine the max value in each array.

        The below snippet demonstrates what I'm talking about with the fake data you listed:

        use List::Util qw(max); use strict; use warnings; my %vals; # Put Data into a Hash of Arrays while (<DATA>) { chomp; my ($key, $val) = split; push @{$vals{$key}}, $val; } for my $key (sort {$a <=> $b} keys %vals) { my $max = max @{$vals{$key}}; print "$key $max\n"; } =prints 1 4 2 7 3 10 =cut __DATA__ 1 3 1 2 1 4 2 5 2 7 3 10 3 0
Re: Excel and Perl
by kcott (Archbishop) on Jun 08, 2011 at 08:09 UTC