Basic file IO in Perl
03 Mar 2017One of the most basic, yet most useful operations you can perform in Perl is working with files. In today’s post, I’ll show you through a few basic patterns to get started with file IO in Perl.
open
The cornerstone to working with a file, is the open function. It takes the following forms:
- open FILEHANDLE,EXPR
- open FILEHANDLE,MODE,EXPR
- open FILEHANDLE,MODE,EXPR,LIST
- open FILEHANDLE,MODE,REFERENCE
- open FILEHANDLE
FILEHANDLE
being the local variable that you’ll use to reference the file.
MODE
determines the type of file access you’re requesting over the file
Mode | Description |
---|---|
< |
File is opened for reading |
> |
File is opened for writing |
>> |
File is opened for appending |
+< |
File is opened for reading and writing |
+> |
File is opened for reading and writing, but clobbered first |
|- |
File is interpreted as a command and piped out |
-| |
File is interpreted as a command and piped in |
<:encoding(UTF-8) |
File is opened for reading and interpreted as UTF-8 |
Throwing on failure
Warning on failure
Diamond operator <>
The diamond-operator is normally used in while
loops and used to iterate through files:
Writing with print
Sending information into file is done so with print.
Finishing up with close
When you’re finished with your files, you’ll use close
These are just the simple operations for working with files in Perl.