First of all, you should always
use strict
and use warnings
for even the most trivial programs. You will also need to declare each of your variables using my
as close as possible to their first use
use lexical file handles and the three-parameter form of open
check the success of every open
call, and die
with a string that includes $!
to show the reason for the failure
Note also that there is no need to explicitly open files named on the command line that appear in @ARGV
: you can just read from them using <>
.
As others have said, it looks like you are reading a file of DOS or Windows origin on a Linux system. Instead of using chomp
, you can remove all trailing whitespace characters from each line using s/\s+\z//
. Since CR and LF both count as "whitespace", this will remove all line terminators from each record. Beware, however, that, if trailing space is significant or if the last field may be blank, then this will also remove spaces and tabs. In that case, s/[\r\n]+\z//
is more appropriate.
This version of your program works fine.
use strict;
use warnings;
@ARGV = 'addr.txt';
open my $out, '>', 'output.txt' or die $!;
while (<>) {
s/\s+\z//;
my @fields = split /\t/;
print $out join("\t", @fields[1, 2, 2]), "\n";
}
close $out or die $!;