in reply to Re: foreach skipping elements
in thread foreach skipping elements
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. :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: foreach skipping elements
by mtmcc (Hermit) on Jul 20, 2013 at 05:22 UTC |