Perl Operators   «Prev  Next»
Lesson 12File test (-X) operators
Objective Create a program that reports file information.

File Test (-X) Operators

Perl has a number of operators for testing the conditions of files. These operators are useful if you want to know if a file is readable, or executable, or if it's a directory, and so on. Because Perl was designed and written on Unix, you will find that many of these operators do not work as expected on Windows NT or other non-Unix operating systems.
If you are using a non-Unix system and are unsure whether a particular operator does what you expect, you can try it from the command line with something like this:

perl -e "print -X 'filename' ? qq(true\n)
: qq(false\n)" 
The example above would normally appear on a single line. It is broken into multiple lines for readability.

Operator Testing

Use the operator you are testing and a suitable filename, in place of -X and filename above. Then you can see if you get the result you expect.
Here are all the file test operators defined in Perl 5, and some common uses.

Using String Operators

As mentioned, the difference between Perl’s functions and operators is a bit vague at times, but for convenience, the punctuation bits are referred to as operators.

Repetition Operator: x

STRING x INTEGER
(STRING) x INTEGER
The x operator is for repetition. It’s often used to repeat a string several times:
my $santa_says = 'ho' x 3.7;
print $santa_says;
The previous code assigns hohoho to $santa_says.
Sometimes you will want to assign a single value multiple times to a list. Just put the string in parentheses to force list context:
my $ho = 'ho';
my @santa_says = ($ho) x 3;

@santa_says now contains the three strings ho, ho, and ho.

XOP Exercise

Click the Exercise link below to practice using file test operators.
XOP Exercise

Perl 6