File Access
File input / output
- There's no prefix character for file handles.
Functions
open
open ( FILEHANDLE, FILENAME )
- Open a file for input and / or output
- Return values, 1 : success, 0 : failure
close
close ( FILEHANDLE )
- Close the file
Filename format
"FILE" # Open FILE for input
"< FILE" # Open FILE for input
"> FILE" # Open FILE for output, creating it if necessary
">> FILE" # Open FILE for appending
"+> FILE" # Open FILE with read/write access
"| CMD" # Open a pipe to CMD
"CMD |" # Open a pipe from CMD
Examples
# Get ready to send the mail
if ( ! open( MAIL, "| $sendmail $recipient" ) ) {
&error("Could not start mail program");
}
if (open(DAT, "data.txt)) { # Open the file for reading.
$first_line=<DAT>; # Read the first line.
@raw_data=<DAT>; # Read the rest of the file into an array.
close(DAT);
}
if (open(DAT,">>data.txt")) { # Open the file for appending.
print DAT "More info\n"; # Append the string to the file.
close(DAT);
}
if (open(DAT,">data.txt")) { # Open the file for writing (overwriting).
print DAT "$Some info\n"; # Write the string to file.
close(DAT);
}
while (<DAT>) { # Assigns each line in turn to $_
print $_; # Print the line to standard output.
}
File functions
unlink
unlink( FILENAME )
- Delete the file
File test operators
-r readable
-x executable
-e exists
-d directory
-t is a tty
-T text file
if (! -e "myfile") { # If the file does not exist
statements;
}
Resources URL:
notes/perl/resources
Sources URL:
notes/perl/sources