Perl - while (<>) 文件处理 [英] Perl - while (<>) file handling

查看:14
本文介绍了Perl - while (<>) 文件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个带有 while( <> ) 的简单程序处理作为参数给出的文件 (./program 1.file 2.file 3.file) 和标准输入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 "
" 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 "
" 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.

如果你想跟踪当前文件句柄中的行号$.,你可以closeARGV文件句柄来重置这个计数器:

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 (&lt;&gt;) 文件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆