Perl Programming Page 4 - Perl: Appending and Writing to Files |
We can use the following command to delete the file: unlink("superhero.txt"); (Note: remember, if you did not put it in the same directory as the code you are writing, you must add the location of the file). You can do the same thing with variables: $my_file="superhero.txt"; unlink($my_file); And voila! Your file is deleted. Of course if you need it later you are screwed, so it is always a good idea to make a backup somewhere in case you need it later. How To Check a File There are several ways to test files within Perl. The funniest to me is the Check Existence, which literally checks to see if a file exists. I guess not everyone can have a super human brain like you and me. Does it Exist?!? Here is the code to see if a file exists: if (-e "superhero.txt") { #whatever you want to occur if the file exists } The -e tells the code to see if the preceding file name exists. You can do the same thing with a variable too of course. $my_file="superhero.txt"; if (-e $my_file) { #whatever you want to occur if the file exists } You can also see if a file exists by measuring the size of the file. For that you would replace -e with -z or -s (z = zero sized file, s= more than zero). $my_file="superhero.txt"; if (-z $my_file) { #whatever you want to occur if the file is zero sized } or
$my_file="superhero.txt"; if (-s $my_file) { #whatever you want to occur if the file is greater than 0 in size } You can of course also test if the file has Text or Binary data: $my_file="superhero.txt"; if (-T $my_file) { #whatever you want to occur if the file is a text file } and
$my_file="superhero.txt"; if (-B $my_file) { #whatever you want to occur if the file is a binary file }
blog comments powered by Disqus |
|
|
|
|
|
|
|