tags:

views:

63

answers:

4

I am trying to do print all of the values of an array from a CSV file. I am sort of manually doing this in the example below. Can someone show me the code for doing this for all of the fields of the array no matter how many fields there are? I'm basically just trying to print each field on a new line.

#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV_XS;



my $file = 'test.csv';

my  $csv = Text::CSV_XS->new ({
 quote_char          => '"',
 escape_char         => '@',
 binary              => 1,
 keep_meta_info      => 0,
 allow_loose_quotes  => 1,
 allow_whitespace    => 1,
 });



open (CSV, "<", $file) or die $!;

while (<CSV>) {
    if ($csv->parse($_)) {
        my @columns = $csv->fields();
print "$columns[0]\r\n";
print "$columns[1]\r\n";
print "$columns[2]\r\n";
print "$columns[3]\r\n";
print "$columns[4]\r\n";
print "$columns[5]\r\n";
print "$columns[6]\r\n";
print "$columns[7]\r\n";
    } else {
        my $err = $csv->error_input;
        print "Failed to parse line: $err";
    }
}
close CSV;
+1  A: 
foreach(@colums)
{
    print "$_\r\n";
}

Instead of all the columns[number].

Alistra
Thank you. That worked great!
XL
+1  A: 

If you just want to print the elements separated by spaces:

print @columns;

If you want to be a bit more fancy, you can use join:

print join("\n", @columns);

If you need to do something more, iterate over it:

foreach (@columns) {
    # do stuff with $_
}
Anon.
I just tried the join function and it also works great. That actually solves another aspect of the script that I am working on. Thanks very much!
XL
Your `join` example does not print a newline after the last item.
mobrule
@mobrule: If this is necessary, then it's trivial to add: `print join("\n", @columns), "\n";`
Anon.
+1  A: 

If you're doing this for diagnostic purposes (as opposed to presentation) you might consider Data::Dumper. In any case it's a good tool to know about if you want a quick printout of more-or-less arbitrary data.

c-urchin
I'll check it out. Thanks!
XL
+2  A: 

For debugging purposes, Data::Dump is my weapon of choice. It basically pretty-prints data structures.

use strict;
use warnings;
use Data::Dump 'dump';

# Do some stuff....

dump @array;     # Unlike Data::Dumper, there's no need to backslash ('\@array')
dump %hash;      # Same goes for hashes
dump $arrayref;  
dump $hashref;   # References handled just as well

There are many other ways to print arrays, of course:

say foreach @columns;           # If you have Perl 5.10+
print $_,"\n" foreach @columns; # If you don't

print "@columns";               # Prints all elements, space-separated by default

The 'best' answer depends on the situation. Why do you need it? What are you working with? And what do you want it for? Then season the code accordingly.

Zaid