But your program will miss the last empty field. In 1|2||3|45|||6|, for example, your program stops too early:

. . NEW: 45 NEW: NEW: NEW: 6

(One empty NEW: line should follow, since separators separate fields, rather than terminate them.)

If that were the only issue, you could just append a single '|' to the input string before the rest of your logic.

The second problem, though, is that your regex converts empty fields to a single space ' '. True, you could easily replace them, but if the field was ' ' in the first place, the value will be destroyed. That may not be a problem depending on the data, but to fix this, and the previous issue, you can make a couple of changes:

$line =~ s!\|!\| !g; . . @new = map { substr $_, 1 } split /\|/, $line;

Or, as the OP suggested he was trying to avoid, he could just add a non-blank field to the end. In that case the entire code reduces to:

my @new = split /\|/, $line . '|sentinel'; $#new--; # Remove sentinel

But of course, split /\|/, $line, -1; still gets my vote. :-)


In reply to Re^2: foreach skipping elements by rjt
in thread foreach skipping elements by tiggyboo

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.