"Perl for Perl Newbies" - Part 2File Input/Output

5. File Input/Output

By now you are probably wondering how perl can be used to interact with the external world, and this is where File Input/Output enters the frame.

In Perl, file I/O is handled by using sessions: you are opening a file for reading or writing (or both), do with it what you want, and then close it. In Perl, filehandles implemented as the so-called globs are placed on a separate namespace than that of the variables. It is generally marked with a starting asterisk (*), which can be omitted if the first letter is a capital one.

To open a file use the open my $my_file_handle, $mode, $file_path; notation, and to close a file use the close($my_file_handle); notation. The $mode determines whether the file will be open for reading, writing, appending or some of them. The following table should give you a quick reference:

>Writing (the original file will be erased before the function starts).
< (or nothing)Reading
>>Appending (the file pointer will start at the end and the file will not be overridden)
+<Read-write, or just write without truncating.

$file_path is the pathname of the file to open relative to the script current working directory (CWD). For instance, the command open I, "<", "../hello.txt"; opens the file "hello.txt" found a directory above the current directory for reading.

Written by Shlomi Fish