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 ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.