How to Delete a File in Perl
Depending on the nature of the PERL program it may be necessary to delete files on disk. For example, if a blank file is created at the beginning of a program and is then written to, it may have to be deleted in order for the program to function correctly. This type of file management is common in some indexing programs. One such instance is when a file whose name never changes must print out dynamic material with each run of the program. In this article you will see how to delete a file by creating a script that creates a text file and then deletes it.
Instructions
-
Deleting a file in PERL
-
1
Check for PERL on your computer. At the c:\ type "perl -v" (no quote marks) and then press "Enter." If there is a version of PERL installed, you will see some text telling you what version you have. If you see this text, skip to Step 3. If not, go on to Step 2.
-
2
Download PERL to your computer. You can do this by going to www.activestate.com and following the instructions for downloading PERL. Once PERL has installed, do Step 1 again.
-
-
3
Download the ConText text editor. You can do this by going to www.contexteditor.org. This is a very good editor for programming in several languages.
-
4
Write code that creates a txt file. In the text editor type the following
open(FL,">file.txt");
print FL "Hello there";This bit of code creates a txt file named "file.txt" and then prints the words "Hello there" in the file. If you run the file and then check the contents of the text file, you will see the words "Hello there" printed out.
Save the file as "delete.pl"
-
5
Write code that deletes the file. This bit of code deletes "file.txt" by employing the "unlink" command. The program then prints out a message that the deletion has been carried out.
unlink "file.txt";
print "File has been deleted"; -
6
Create the full program. To do this, add the contents in Step 5 to those in Step 4. The program should look like the following:
open(FL,">file.txt");
print FL "Hello there";
unlink "file.txt";
print "File has been deleted";
-
1
Tips & Warnings
PERL downloads very easily. It may take about 10 minutes, but you do not have to do anything special.
Make sure you do not accidentally unlink a file that you need. Make sure to always put the ';' after statements Never capitalize the 'print' command. Notice that the 'FL' is just a file handle that I created. It can be anything you want as long as it is in uppercase, e.g., 'MY_FILE'