views:

70

answers:

3

This is going to seem extremely trivial, but it just doesn't make any sense to me.

I have the following snippit of code:

foreach $i (@inputtext)
{
@line = split(/\|/, $i);
 foreach $j (@line)
 {
  print "$j, ";  
 }
}

The input is three of the following lines, identical:

98465895|No idea what goes here|123 anywhere lane|city|ST|55555|data1|pass1|data2|pass2|data3|pass3|more stuff

The output ends up being this though:

98465895, No idea what goes here, 123 anywhere lane, city, ST, 55555, data1, pass1, data2, pass2, data3, pass3, more stuff
, 98465895, No idea what goes here, 123 anywhere lane, city, ST, 55555, data1, pass1, data2, pass2, data3, pass3, more stuff
, 98465895, No idea what goes here, 123 anywhere lane, city, ST, 55555, data1, pass1, data2, pass2, data3, pass3, more stuff

There is no logical reason I can see that would create an endline inside a print statement, throwing the comma onto the next line, and messing up the next lines of the output. Anyone have any suggestions?

Thanks

+3  A: 

We can't see what's reading from the file. Are you calling chomp on your input text to get rid of the trailing newline?

Also, instead of doing that for loop to join the fields with commas, do this:

print join( ', ', @line );
Andy Lester
yeah, it sadly was as simple as a stupid chomp statement...
ThePirateSheep
+2  A: 

I bet $i contains a newline character before you split it. Try chomping it first.

aschepler
+1  A: 

I'm not exactly sure whats before this code, but I'd bet it's something like this:

open FILE, 'filename';
@inputtext = <FILE>;

Perl is optimized for you to approach the problem differently:

use strict; use warnings;  # helps you avoid errors early

open my $file, '<', 'filename' or die $!;

while (<$file>) {                   # loads the next line from $file into $_
    chomp;                          # strip newline from $_
    print join ', ' => split /\|/;  # split uses $_ without an arg
    # or use split's output for anything else
}

if you are using this code in a subroutine, be sure to local $_; before the while loop.

Eric Strom