Perl Operators   «Prev 

Reading a Perl File

In Windows 2000/XP/Vista/Windows 7, you cannot use a pipe to a Perl program if you call the program from an association.
In other words, this will not work:
You can read an entire file into an array like this:

type foo.txt | test.pl

But this will:
type foo.txt | c:\perl\bin\perl test.pl

@array = <FILEHANDLE>

Or, just one line from a file like this:
$scalar = <FILEHANDLE>

Or you can use the special form of the while loop for reading a file. This will put each line of the file in the special $_ variable:
while(<FILEHANDLE>) {
  # $_ has the current line of the file
  }

For example, this program opens a file and prints its contents to the console (just like cat in Unix or TYPE in DOS):
#!/usr/bin/perl -w

$filename = shift;
open(HANDLE, "<$filename")
 or die "$filename: $!\n";
while(<HANDLE>) { print }
close HANDLE;

The die function is often used for an error exit. It exits and prints a message.
The special variable $! contains the last error message from the operating system.
There is also special empty filehandle <> that can be used in this circumstance.
It will automatically open and read any files which are listed on the command line; or if there are not any, it will use the standard input stream (usually the keyboard or a pipe from another program). That allows you to write the above program like this:

#!/usr/bin/perl -w
while(<>) 
{ 
print 
}