简体   繁体   中英

New to perl… having problems with chomp

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

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM