Reputation: 7521
I am trying to learn perl programming and am using it to read a file from a contest;
#!/usr/local/bin/perl
use warnings;
open(FILE, <~/source/test.txt>);
@array = <FILE>;
$number = shift @array;
while($number--) {
chomp($key = shift @array);
chomp($message = shift @array);
print "Key: $key";
print "Message: $message";
}
print "\n";
close(FILE);
The file contains a number, N, then there are 2 * N lines that follow which is how many key/message pair's there are.
But when I do this program, it only prints out the last "message" and nothing else... it doesn't print anything else. If I remove the chomps it works as intended, but with the chomps there it just cuts everything off... any ideas why?
//EDIT: removed the -w
Upvotes: 1
Views: 487
Reputation: 386396
You are reading a DOS/Win text file on a unix box. Using chomp
, you are removing the "LF" of "CRLF", but leaving the "CR", causing all your lines to be shown one atop the other.
#!/usr/local/bin/perl -w
use strict; # Do use this!
use warnings;
open(my $fh, '<', "$ENV{HOME}/source/test.txt") or die $!;
my @array = <$fh>;
s/\s+\z// for @array; # Universal chomp
my $number = shift(@array);
while ($number--) {
my $key = shift(@array);
my $message = shift(@array);
print "Key: $key\n";
print "Message: $message\n";
}
Upvotes: 8