Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Write array contents to csv file

by learner@perl (Novice)
on Jul 11, 2013 at 10:46 UTC ( #1043688=perlquestion: print w/ replies, xml ) Need Help??
learner@perl has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

I am pushing some values into array and then writing the values from array to csv file. i have used the below code

my $csvfile; push (@report,(join "\t", $empid, @array),"\n") foreach (@report) { print $_; print $csvfile $_; }

when i execute the code, i am getting below output on command prompt

JKSLK 19890101 20000101 France ALMERIA 100000.00 BCF +GHK

on csv file, i am getting below output

Name DOB DOJ Country Region Salary Place JKSLK1989010120000101FranceALMERIA100000.00BCFGHK

How can i write the values on csv file in tab delimited formatm please suggestions

Thanks in advance

Comment on Write array contents to csv file
Select or Download Code
Re: Write array contents to csv file
by Anonymous Monk on Jul 11, 2013 at 10:59 UTC
Re: Write array contents to csv file
by OfficeLinebacker (Chaplain) on Jul 11, 2013 at 12:30 UTC
    I'm trying to figure out what the $empid and @array do. Why don't you split out the statements so you can diagnose what's going on better? Or use an Array of Arrays? Also, do you have to put another set of parens around the list you created with @empid and @array, e.g.
    my $line = join /\t/ , ($empid, @array); push @report, $line;
      Hi,

      $empid contains numeric value like 12 and @array contains values like Name DOB DOJ Country Place Salary, i am pushing all the values from $empid and @array to @report using join and all values are tab delimited

      i used the code below and executed

      my $line = join /\t/ , ($empid, @array); push @report, $line;

      Output i got as below

      Name DOB DOJ Country Region Salary Place JKSLK1989010120000101FranceALMERIA100000.00BCFGHK

      Output expected

      Name DOB DOJ Country Region Salary Place JKSLK 1989010120000101 France ALMERIA 100000.00BCFGHK

      i am trying to write this output to csv file, how can i do that, any solution please

        Are you viewing the csv file in Excel ? If so, rename it to report.xls and then see what you get.

        poj
Re: Write array contents to csv file
by mtmcc (Hermit) on Jul 11, 2013 at 14:35 UTC
    If you give working code and useable data, you'll probably get advice on a working solution much faster.

    Why don't you just add $empid to your array, and then join them in a separate statement, like;

    push(@array, $empid); $string = join("\t", @array); print STDOUT "$string\n";

    Michael
Re: Write array contents to csv file
by marinersk (Chaplain) on Jul 11, 2013 at 20:54 UTC

    While your efforts to honor the brevity requirement for posted code snippets is admirable -- and I truly mean this and thank you for making the effort -- it is often critical to also honor the functional requirement.

    That said, some notes:

    1. You are not writing a CSV file. You are writing a TSV file:
      • CSV means Comma-Separated Values.
      • TSV means Tab-Separated Values.
    2. Your code doesn't work:
      #!/usr/bin/perl use strict; my $csvfile; push (@report,(join "\t", $empid, @array),"\n") foreach (@report) { print $_; print $csvfile $_; } exit; __END__

      Produces:

      C:\Steve\Dev\PerlMonks\P-2013-07-11@1436-CSV-Fail>perl csvfail.pl Global symbol "@report" requires explicit package name at csvfail.pl l +ine 6. Global symbol "$empid" requires explicit package name at csvfail.pl li +ne 6. Global symbol "@array" requires explicit package name at csvfail.pl li +ne 6. Global symbol "@report" requires explicit package name at csvfail.pl l +ine 7. syntax error at csvfail.pl line 7, near ") {" syntax error at csvfail.pl line 10, near "}" Execution of csvfail.pl aborted due to compilation errors.

    Because I can see where you're going with this data, I will play with the code and see if I can produce a small version which facilitates debugging.

    See you in a few minutes. :-)

      Okay, adding test data, fixing most of the syntax errors, breaking out the steps, and adding debugging statements (collectively referred to as "Troubleshooting by firepower" by an old friend in the business), we have some clues for you to examine:

      #!/usr/bin/perl -w use strict; # Set up test data my @header = ( 'Name', 'DOB', 'DOJ', 'Country', 'Region', 'Salary', 'Place', ); my @data = ( 'JKSLK', 19890101, 20000101, 'France', 'ALMERIA', 100000.00, 'BCFGHK', ); my $empid = 123456; # Set up working data my @report = (); my @array = (); # Initialize push @array, @header; # Do the work my $csvfile; # SKM: What is this for, exactly? my $reportLine = join "\t", ($empid, @array); print "DEBUG: \$reportLine = [$reportLine]\n"; push @report,$reportLine,"\n"; foreach my $reportElement (@report) { print "DEBUG: \$reportElement = [$reportElement]\n"; } foreach (@report) { print $_; print $csvfile $_; } exit; __END__

      This produces:

      C:\Steve\Dev\PerlMonks\P-2013-07-11@1436-CSV-Fail>perl csvfail2.pl DEBUG: $reportLine = [123456 Name DOB DOJ Country Region + Salary Place] DEBUG: $reportElement = [123456 Name DOB DOJ Countr +y Region Salary Place] DEBUG: $reportElement = [ ] Can't use an undefined value as a symbol reference at csvfail2.pl line + 54. 123456 Name DOB DOJ Country Region Salary Place

      My observations:

      1. The tabs are in the data. You already knew that, of course, since when you display it directly to the console you get the tabs. Your real issue is in how to get the information into a file, as you have stated. But there are other issues here which should be resolved first.
      2. You don't seem to have the syntax figured out for writing to a file from Perl. Suggest you review the open, print, and close functions in the documentation, and look for code examples. It is rare to need to a scalar in place of a hard-coded file handle.
      3. You are putting the newline on its own element in @report instead of simply appending it to the line. This is probably not what you intended, though it's not technically an error.
      4. $empid is handled oddly here; I can see a number of reasons you are including it in the snippet, but without a functioning snippet, they are just guesses.
      5. It looks like you are building a prototype of the logic to be used inside a loop. Not a bad approach, but coding up a fake loop is very little effort and in my humble opinion is better than writing linear code and then converting it later into a loop. Your mileage may vary.

      I don't want to just solve the problem for you, since the point of PerlMonks is, generally, to help you become a better Perl programmer. That is best done if you do some of the analysis yourself.

      I'd be happy to answer any questions you have about what this example is showing us, or adjustments to the code which more clearly refine the scope of your question.

Re: Write array contents to csv file
by Anonymous Monk on Jul 12, 2013 at 02:53 UTC

    Hi,

    I created a tab delimited file using notepad, and saved it with a .csv extension.

    I opened it it Excel and the tabs were missing.

    I then copied it and changed the extension to .txt.

    The tabs were there in Excel ( after a bit of palaver ).

    Might solve the problem, might not.

    J.C.

      Ah, yes, that's right, Excel leans on the file type in the name more heavily than expected in some cases.

      Might be that merely naming the file with a .CSV type is masking the operation.

      Good catch.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1043688]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2014-09-24 01:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (244 votes), past polls