Hello Joma, and welcome to the Monastery!

You say your second script prints only 1, but when I run it I get the same result as you show for the first script. However, there is a logic error in your code: the foreach loop needs to be moved to within the while loop, otherwise you will only ever print out the fields for the final line read from the CSV file. (This isn’t apparent when there is only one line in the input file.) And you should always use strict and use warnings:

use strict; use warnings; use Text::ParseWords; while (my $line = <DATA>) { my @fields = quotewords(',', 0, $line); for my $field (0 .. $#fields) { print $field + 1, " $fields[$field]\n"; } } __DATA__ "earth",1,,"moon",9.374 "mars",2,,"phobos",,"deimos",

Output:

14:17 >perl 1671_SoPW.pl 1 earth 2 1 3 4 moon 5 9.374 1 mars 2 2 3 4 phobos 5 6 deimos 7 14:20 >

BTW, good job on adding <code>...</code> tags to your second post. Two tips: (1) It would have been better to update your first post. When you post as a logged-in user, you can always update that post later. (Click on the “Edit” button in the top, right-hand part of the screen.) Just remember to mark updates as such to avoid confusing readers of the thread. (2) You should also put the output you get into <code> tags, to make it easier to read.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: Parsing CSV file by Athanasius
in thread Parsing CSV file by Joma

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.