in reply to Re: Read CSV with column mapping
in thread Read CSV with column mapping

Thanks. Following I am providing ReadCSV.pm, parameters.csv and getvalue.pl. It is working fine but I want to avoid any comments (starts with #) in parameters.csv and also any blank lines. How can I do that in ReadCSV.pm ?

ReadCSV.pm
package ReadCSV; use strict; use warnings; use Data::Dumper; use Text::CSV_XS; use IO::File; # Implementation: sub csv_file_hashref { my ($filename) = @_; my $csv_fh = IO::File->new($filename, 'r'); my $csv = Text::CSV_XS->new (); my %output_hash; while(my $colref = $csv->getline ($csv_fh)) { $output_hash{shift @{$colref}} = $colref; } return \%output_hash; } 1;
parameters.conf
abc xyz,10 xyz pqr,2 pqr stq,0.1
getvalue.pl
use strict; use warnings; use Data::Dumper; use ReadCSV; my $hash_ref = ReadCSV::csv_file_hashref('parameters.conf'); foreach my $key (sort keys %{$hash_ref}){ print qq{$key:}; print join q{,}, @{$hash_ref->{$key}}; print qq{\n}; }

Replies are listed 'Best First'.
Re^3: Read CSV with column mapping
by Corion (Patriarch) on Dec 14, 2018 at 22:44 UTC

    In the loop where you read the CSV, only store the row if it is not a comment?

    Do the same for the blank lines?

      I have tried adding if conditions as shown in following code but it is not skipping to add comment line and empty line. Am I doing something wrong?

      while(my $colref = $csv->getline ($csv_fh)) { if (scalar(@$colref) =~ /^#/) { last; } if (scalar(@$colref) =~ /^s+$/) { last; } $output_hash{shift @{$colref}} = $colref; }
      config file
      #ksjlasjda abc xyz,10 xyz pqr,2 pqr stq,0.1

        scalar(@$colref) is the number of items found in the column, it would never contain a '#' symbol.

        $colref->[0] is the first item on the line read in, it could contain a # symbol.

        if ($colref->[0] =~ /^#/) { next; }

        Notice i said next rather than last. next will go on to the next row, last will end the do loop and stop reading any more lines.

        the next condition is a touch more tricky.

        my $anynonblank=0; for my $item (@$colref){ unless ($item =~ /^\s+$/) { $anynonblank=1; last; } } unless ($anynonblank) { next; }
        See we have to test all of the items in this case. Note th use of last here, as soon as we have found any nonblank we dont have to check anymore.

        edit: opps , fixed as per Re^6: Read CSV with column mapping below