Opening Files
- Use the open() function to open a file for processing
- Prefix the filename with a character to define how to open it:
- "<" for input from an existing file
- ">" to create for output
- ">>" to append to a (possibly existing) file
- If open() fails, it returns false, and sets the $! special variable.
- Example:
open( IN, "<myfile.txt" ) or die "Can't open myfile.txt: $!";
- Remember that Perl will translate slashes to backslashes as
necessary.
Reading
Files
- Use the <> (or
the "diamond operator") to read in a line from a file handle.
- If the diamond operator is called without getting assigned to
anything, it gets assigned to $_
- If the file pointer is at EOF, undef is returned.
Putting them together
- The following reads in your autoexec.bat file, and writes it out
with line numbers prepended:
#!perl -w
use strict;
my $infile = "c:/autoexec.bat";
my $outfile = "numbered.txt";
open( IN, "<$infile" ) or die "Can't open $infile for input: $!";
open( OUT, ">$outfile" ) or die "Can't open $outfile for output: $!";
my $n;
while ( my $line = <IN> ) {
++$n;
print OUT "$n: $line";
}
close OUT;
close IN; Standard Input
- Special filehandle STDIN is always open.
- Read from it like you'd read from any file.
Fileglobbing
- The <> operator
does fileglobbing.
- Fileglobbing finds all files matching a pattern and returns a list
of filenames.
my @executables =
<*.exe *.com *.cmd *.bat>
- Fileglobbing only works in a given directory. For recursive
searching, you have to use the File::Find module.
- The glob() function
does exactly the same thing, if you don't like the <> construct.
|
|
|