Learning Perl

Learning PerlSearch this book
Previous: 10.5 The -x File TestsChapter 10
Filehandles and File Tests
Next: 10.7 Exercises
 

10.6 The stat and lstat Functions

While these file tests are fine for testing various attributes regarding a particular file or filehandle, they don't tell the whole story. For example, there's no file test that returns the number of links to a file. To get at the remaining information about a file, merely call the stat function, which returns pretty much everything that the stat POSIX system call returns (hopefully more than you want to know).

The operand to stat is a filehandle or an expression that evaluates to a filename. The return value is either undef, indicating that the stat failed, or a 13-element list,[7] most easily described using the following list of scalar variables:

($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,
 $size,$atime,$mtime,$ctime,$blksize,$blocks) = stat(...)

[7] If you have a hard time remembering the order of stat's return values, you might look at the File::stat module, first introduced in release 5.004 of Perl. It provides access such as:

$file_owner = stat($filename)->uid;

The names here refer to the parts of the stat structure, described in detail in your stat (2) manpage. You should probably look there for the detailed descriptions.

For example, to get the user ID and the group ID of the password file, let's try:

($uid, $gid) = (stat("/etc/passwd"))[4,5];

And that's the way it goes.

Invoking the stat function on the name of a symbolic link returns information on what a symbolic link points at, not information about the symbolic link itself (unless the link just happens to be pointing at nothing currently accessible). If you need the (mostly useless) information about the symbolic link itself, use lstat rather than stat (which returns the same information in the same order). The lstat function works like stat on things that aren't symbolic links.

Like the file tests, the operand of stat or lstat defaults to $_ , meaning that the stat will be performed on the file named by the scalar variable $_.


Previous: 10.5 The -x File TestsLearning PerlNext: 10.7 Exercises
10.5 The -x File TestsBook Index10.7 Exercises