Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Read CSV with column mapping

by Corion (Patriarch)
on Nov 25, 2018 at 07:36 UTC ( [id://1226285]=note: print w/replies, xml ) Need Help??


in reply to Read CSV with column mapping

Have you looked at Text::CSV_XS? It can read CSV files and convert them to hashrefs respecting the headers.

Maybe when you have written the code, you can post the relevant parts here if you still need help.

Replies are listed 'Best First'.
Re^2: Read CSV with column mapping
by coretele (Novice) on Dec 14, 2018 at 22:01 UTC

    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}; }

      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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1226285]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2024-04-23 16:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found