WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Intermediate · question 31 of 100

Explain how to use Perl’s file test operators, like ’-e’, ’-f’, and ’-d’.?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

Perl’s file test operators are used to perform tests on different characteristics of files and directories. These operators are used to check for the existence of a particular file, determine whether it is a regular file or a directory or a symbolic link, or other attributes such as the file size, modification time, and permissions.

Here is a brief explanation of some commonly used file test operators in Perl:

1. ‘-e‘ operator: The ‘-e‘ operator checks whether a file exists or not. It returns a true (1) value if the file exists and is accessible.

Example:

if (-e "/path/to/file.txt") {
   print "File exists!n";
} else {
   print "File does not exist!n";
}

2. ‘-f‘ operator: The ‘-f‘ operator checks whether a file is a regular file or not. It returns true (1) if the file is a regular file.

Example:

if (-f "/path/to/file.txt") {
   print "File is a regular file!n";
} else {
   print "File is not a regular file!n";
}

3. ‘-d‘ operator: The ‘-d‘ operator checks whether a file is a directory or not. It returns true (1) if the file is a directory.

Example:

if (-d "/path/to/dir") {
   print "This is a directory!n";
} else {
   print "This is not a directory!n";
}

There are other file test operators that can be used in Perl, such as ‘-s‘ to get the file size, ‘-M‘ to get the age of the file (in days), and ‘-r‘, ‘-w‘ and ‘-x‘ to check for read, write, and execute permissions.

The file test operators can also be combined using logical operators such as ‘&&‘ (and) and ‘||‘ (or) to perform more complex tests.

Example:

if (-e "/path/to/file.txt" && -f "/path/to/file.txt") {
   print "File exists and is a regular file!n";
} else {
   print "File does not exist or is not a regular file!n";
}

In conclusion, the file test operators in Perl are very useful for checking different properties of files and directories, and can be used in a variety of programming tasks.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics