How to Create a File Using Perl
Perl opens files for reading and writing using the "open" function. Counter-intuitively, open is also the function used to create files. The key is to use the MODE argument to enter a mode that allows file creation. Unfortunately, Perl syntax often makes use of obscure punctuation marks to stand in for commands. This makes it easier for experienced Perl developers to quickly create software, but difficult for beginners to know what their options are.
Instructions
-
-
1
Open your favorite text editor.
-
2
Type the following Perl command into the text editor:
open FILE, ">", "filename.txt" or die $!;
close(FILE);
-
-
3
Save your work. The script, when double-clicked, will create a new empty file named "filename.txt." Alternatively, you can right-click the script and select "Run" or type "perl scriptname" in the command prompt.
-
1
Tips & Warnings
The key part of the command is the ">." This is the mode argument. A single ">" puts Perl in write mode and creates a new file if one doesn't already exist. It also empties any existing file. If you want to create a new file if one doesn't exist, but leave any existing file intact, then use the "append" mode by using ">>" rather than ">."
Perl can't bypass file access restrictions imposed by the operating system. If you attempt to create a file in a place where you aren't permitted, such as in another user's home directory, the command may fail.