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

Hi, I am trying to write a line to the CSV using Class::CSV. but I am not able to write it to the file.

I am running below code:

#!/usr/bin/perl -w use strict; use Class::CSV; my $report_csv = Class::CSV->new ( filename => "final.csv", fields => [qw/VM_Name VM_Cluster +vFiler_IP vFiler_Cluster MisMatch/], ); $report_csv->add_line( { VM_Name => "VM1", VM_Cluster => "CLUST +ER_1", vFiler_IP => "1.1.1 +.1", vFiler_Cluster=> "CLUST +ER_2", MisMatch => "What_ +is_that", } ); $report_csv->print();

so,

$report_csv->print();

code prints the CSV on the console but not to the file "final.csv" which i have specified on the top. AFAIK, we need a file handle to write to a file but I don't seem to find it for Class::CSV, so could you tell me how to write the output of

$report_csv->print();

to a file (final.csv). OR should I be using any other module on CPAN like Text::CSV

Replies are listed 'Best First'.
Re: Class::CSV : How to write to CSV file?
by Athanasius (Cardinal) on Jul 02, 2012 at 07:12 UTC

    Or, just write the output manually using the string() method:

    #!/usr/bin/perl use strict; use warnings; use Class::CSV; my $report_csv = Class::CSV->new ( fields => [qw/VM_Name VM_Cluster vFiler_IP vFiler +_Cluster MisMatch/], ); $report_csv->add_line( { VM_Name => "VM1", VM_Cluster => "CLUSTER_1", vFiler_IP => "1.1.1.1", vFiler_Cluster => "CLUSTER_2", MisMatch => "What_is_that", } ); my $cvs_as_string = $report_csv->string(); my $outfile = 'final.csv'; open(my $fh, '>', $outfile) or die "Unable to open file '$outfile' for + writing: $!"; print $fh $cvs_as_string; close($fh) or die "Unable to close file '$outfile': $ +!";

    HTH,

    Athanasius <°(((><contra mundum

      Perfect. it is working as I wanted. thanks Athanasius.
Re: Class::CSV : How to write to CSV file?
by kcott (Archbishop) on Jul 02, 2012 at 06:59 UTC

    According to the documentation (from the link you provide) new() doesn't accept the filename option.

    The other Class::CSV Constructor, parse(), does accept this option. This is probably what you need.

    -- Ken

Re: Class::CSV : How to write to CSV file?
by Anonymous Monk on Jul 02, 2012 at 07:14 UTC

    Hi, I am trying to write a line to the CSV using Class::CSV. but I am not able to write it to the file.

    Take a look inside, it doesn't support writing to files :) It also has no actual tests -- I would ditch this module in a hurry

    OR should I be using any other module on CPAN like Text::CSV

    Seeing how you're not using any of the methody-classy-ness of Class::CSV, and seeing how Class::CSV is unfinished and untested, yeah, stick with Text::CSV, it does everything you're trying to do