- Web Development Tutorials

File Checking

How to get information about a file
There are some short expressions in Perl that allow you to test files, which is handy if you want to check what a file allows before using it, or if it exists at all. We'll look at a few of the common tests in this section.


To see if a file exists before using it, we can use:

if (-e "filename.cgi")
 #proceed with your code

The -e part is the existence test. After that we have a space, followed by the file we want to test. As in the other sections, we could also use a variable to hold the file name:

if (-e $neededfile)
 #proceed with your code

Now, you can do something based on whether or not the file is there. If it is not, you can give an error page or move on to something else.

Two other existence tests you can use may help if you need to know whether or not the file has anything in it:

File exists, has a size of zero: -z
File exists, has non-zero size: -s

Readable, Writable, or Executable

To see if the file is allowed to be read, written to, or executed we can use these:

Readable: -r
Writable: -w
Executable: -x

So, if we want to check whether we can read a file before we try to open it, we could do this:

if (-r $readfile)
 #proceed with your code

The same goes for the writable and executable tests. These can be a handy way to keep from trying to write to files that don't have write permissions, and various other things.

Text or Binary

You can test the file to see if it is text or if it is binary using these:

Text File: -T
Binary File: -B

They work the same way as the others as well.

Multiple Tests

You can test for two or more things at a time using the "and" (&&) or the "or" ( || ) operators. So, if you want to know if a file exists and is readable before opening it, you could do this:

if ( (-e $readfile) && (-r $readfile) )
 #proceed with your code

File tests are helpful in applications that make use of files often in the code. Using these can help avoid errors, or alert you to an error that needs to be fixed (a required file not able to be read, for instance). Well, have fun testing those files!

Well, that's all for now, let's go on to: Reading Directories.

Copyright © The Web Design Resource. All rights reserved. | Contact Us | Privacy Policy