Getting File Information in Perl



You can test certain features very quickly within Perl using a series of test operators known collectively as -X tests. For example, to perform a quick test of the various permissions on a file, you might use a script like this −

#/usr/bin/perl
my $file = "/usr/test/file1.txt";
my (@description, $size);
if (-e $file) {
   push @description, 'binary' if (-B _);
   push @description, 'a socket' if (-S _);
   push @description, 'a text file' if (-T _);
   push @description, 'a block special file' if (-b _);
   push @description, 'a character special file' if (-c _);
   push @description, 'a directory' if (-d _);
   push @description, 'executable' if (-x _);
   push @description, (($size = -s _)) ? "$size bytes" : 'empty';
   print "$file is ", join(', ',@description),"\n";
}

Here is the list of features, which you can check for a file or directory −

Sr.No Operator & Definition
1 -A
Script start time minus file last access time, in days.
2 -B
Is it a binary file?
3 -C
Script start time minus file last inode change time, in days.
4 -M
Script start time minus file modification time, in days.
5 -O
Is the file owned by the real user ID?
6 -R
Is the file readable by the real user ID or real group?
7 -S
Is the file a socket?
8 -T
Is it a text file?
9 -W
Is the file writable by the real user ID or real group?
10 -X
Is the file executable by the real user ID or real group?
11 -b
Is it a block special file?
12 -c
Is it a character special file?
13 -d
Is the file a directory?
14 -e
Does the file exist?
15 -f
Is it a plain file?
16 -g
Does the file have the setgid bit set?
17 -k
Does the file have the sticky bit set?
18 -l
Is the file a symbolic link?
19 -o
Is the file owned by the effective user ID?
20 -p
Is the file a named pipe?
21 -r
Is the file readable by the effective user or group ID?
22 -s
Returns the size of the file, zero size = empty file.
23 -t
Is the filehandle opened by a TTY (terminal)?
24 -u
Does the file have the setuid bit set?
25 -w
Is the file writable by the effective user or group ID?
26 -x
Is the file executable by the effective user or group ID?
27 -z
Is the file size zero?
Updated on: 2019-11-29T10:29:21+05:30

559 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements