简体   繁体   English

Perl的新手...排骨有问题

[英]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; 我正在尝试学习Perl编程,并正在使用它来读取比赛中的文件;

#!/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. 该文件包含一个数字N,然后跟随2 * N行,这是多少个键/消息对。

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 //编辑:删除了-w

You are reading a DOS/Win text file on a unix box. 您正在unix框上读取DOS / Win文本文件。 Using chomp , you are removing the "LF" of "CRLF", but leaving the "CR", causing all your lines to be shown one atop the other. 使用chomp ,您将删除“ CRLF”的“ LF”,但保留“ CR”,从而使所有行都显示在另一行之上。

#!/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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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