in reply to Finding Empty Columns

How can I determine if the entire column consists of zero data?
Three things:
  1. Which column?
  2. Why not let perl open the file for you?
  3. Wouldn't it be better to make an array of records, rather than a hash of records?
my @rows = map { chomp; [ split /;/ ] } <>; # now you have an array of arrays (rows of columns) my $column = 1; # which column to check for 0 in? if ( grep { $_->[$column] ne "0" } @rows ) { print "Column $column does NOT consist of all 0's.\n"; } # you could extract the contents of just that column, if you need to +: my @column1 = map { $_->[1] } @rows;

jdporter
The 6th Rule of Perl Club is -- There is no Rule #6.

Replies are listed 'Best First'.
Re: Re: Finding Empty Columns
by Anonymous Monk on Feb 14, 2003 at 20:48 UTC
    This is my problem. I have apoximately 240 columns of data.
    I need to determine which columns consist of "0.000000", and disregard them before printing them out.

    Thanks

      So, for example, if column 1 is 0.0 in all rows, then don't print out that column?

      Maybe this will do the trick: (assumes all rows have equal number of cells)
      my @rows = map { chomp; [ split /;/ ] } <>; # now you have an array of arrays (rows of columns) my @non_zero_columns = grep { my $column = $_; grep { $_->[$column] != 0 } @rows } 0 .. $#{$rows[0]}; for ( @rows ) { print "@{$_}[ @non_zero_columns ]\n"; }
      However, that's highly sub-optimal if there are few zero fields in the table.
      This would be better:
      my %zero_columns; @zero_columns{ 0 .. $#{$rows[0]} } = (); # initially, all columns mi +ght have 0. # eliminate any columns that have non-0 in any row: for ( my $r = 0; $r <= $#rows && keys %zero_columns; $r++ ) { for my $i ( keys %zero_columns ) { $rows[$r][$i] == 0 or delete $zero_columns{$i}; } } # invert the set: my @non_zero_columns = grep { ! exists $zero_columns{$_} } 0 .. $#{$rows[0]};

      jdporter
      The 6th Rule of Perl Club is -- There is no Rule #6.