Free Perl Tutorials

How To View Stats On File In PERL

Perhaps you are looking for how large your file size is? Here is how we can find the size of a file using PERL!

First, we choose which file we want to check the statistics on using PERL. In this case, we'll create a file called "test.txt", and use that one. The stats function (or statistics function) in PERL is very versatile in that it can return any one of 13 stats on the file listed below:

0 dev device number of filesystem
1 ino inode number
2 mode file mode (type and permissions)
3 nlink number of (hard) links to the file
4 uid numeric user ID of file's owner
5 gid numeric group ID of file's owner
6 rdev the device identifier (special files only)
7 size total size of file, in bytes
8 atime last access time in seconds since the epoch
9 mtime last modify time in seconds since the epoch
10 ctime inode change time in seconds since the epoch (*)
11 blksize preferred block size for file system I/O
12 blocks actual number of blocks allocated

Yes there are 13 values...remember we count from 0 in PERL!

Ok, so now we want to know the code to have the program look at the file and return whatever stat we want. For this example, we'll look at the file size of a particular file:

#First, we set the file we want to check equal to a string
$myfile = "test.txt";

#Next we call the function that we want (in this case it is the 7th
#element of the stat function in PERL)
$size = (stat $myfile) [7];

#Print the results
print = "My file is $size bytes large\n";

Now if we wanted to know when a file was last accessed, we simply change the 7 to an 8! Easy, right?