hoopajoo.net
To stat() or not to stat()
To stat() or not to stat()
⇐ Back to Files

Questions, comments, or corrections? Send me a message.

The stat() function call is very useful in any language. It will give back lots of file information like type, size, modified, and so on. While the size and time returns are easy enough to understand, there are several other that are much harder to work with.

Thankfully, though, perl has several built in unary operators that can do simple file checking similar to the shell. Some of the more useful are (ripped from the perlfunc man page):

-e  File exists.
-z  File has zero size.
-s  File has nonzero size (returns size).
-f  File is a plain file.
-d  File is a directory.
-l  File is a symbolic link.
There are lots of others, search for '-X' on the perfunc man page. Usage of these is simple, just like the shell. For example, a simple test if something is a file, directory, or even exists, might look like this:
$myfile = '/tmp/somefile';
if( ! -e $myfile )
{
  print "Does not exist\n";
}elsif( -d $myfile )
{
  print "It's a directory!\n";
}elsif( -f $myfile )
{
  print "A file, for sure!\n";
}else
{
  print "hrmmm... dunno..\n";
}
This is a simple if/then/else that checks /tmp/somefile to see if it exists, is a file, is a directory, and then gives up. It's that easy, and a lot easier than using stat() then &'ing together some bitmasks.