Perl - while (<>) file handling

Mantas Marcinkus picture Mantas Marcinkus · Feb 17, 2013 · Viewed 59.3k times · Source

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 $_;
}

Answer

TLP picture TLP · Feb 17, 2013

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.

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