ThePirateSheep
ThePirateSheep

Reputation: 3

Perl Output issues

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

Upvotes: 0

Views: 111

Answers (3)

Eric Strom
Eric Strom

Reputation: 40142

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.

Upvotes: 1

aschepler
aschepler

Reputation: 72271

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

Upvotes: 2

Andy Lester
Andy Lester

Reputation: 93636

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 );

Upvotes: 3

Related Questions