Perl-while(<>)文件处理 [英] Perl - while (<>) file handling
问题描述
一个带有 while(<>)
的简单程序处理作为参数给出的文件( ./ program 1.file 2.file 3。文件
)和Unix系统的标准输入。
A simple program with while( <> )
handles files given as arguments (./program 1.file 2.file 3.file
) and standard input of Unix systems.
我认为它是将它们连接成一个文件,并且逐行进行。问题是,我怎么知道我正在使用第一个文件?然后是第二个。
I think it concatenates them together in one file and work is line by line. The problem is, how do I know that I'm working with the first file? And then with the second one.
举一个简单的例子,我想在一行中打印文件的内容。
For a simple example, I want to print the file's content in one line.
while( <> ){
print "\n" if (it's the second file already);
print $_;
}
推荐答案
钻石运算符不连接文件,它只是打开并连续读取它们。您如何控制它取决于您需要如何控制它。检查何时读取文件最后一行的一种简单方法是使用 eof
:
The diamond operator does not concatenate the files, it just opens and reads them consecutively. How you control this depends on how you need it controlled. A simple way to check when we have read the last line of a file is to use eof
:
while (<>) {
chomp; # remove newline
print; # print the line
print "\n" if eof; # at end of file, print a newline
}
跟踪您要处理的文件的顺序
You can also consider a counter to keep track of which file in order you are processing
$counter++ if eof;
请注意,此计数将在列表的最后一行处加一。文件,因此请不要过早使用它。
Note that this count will increase by one at the last line of the file, so do not use it prematurely.
如果要跟踪行号 $。
当前文件句柄,您可以关闭
ARGV文件句柄来重置此计数器:
If you want to keep track of line number $.
in the current file handle, you can close
the ARGV file handle to reset this counter:
while (<>) {
print "line $. : ", $_;
close ARGV if eof;
}
这篇关于Perl-while(<>)文件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!