Skip to Content
Learning Perl, 7th Edition
book

Learning Perl, 7th Edition

by Randal L. Schwartz, brian d foy, Tom Phoenix
October 2016
Beginner
391 pages
10h 38m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 7th Edition

Chapter 12. File Tests

Earlier, we showed you how to open a filehandle for output. Normally, that creates a new file, wiping out any existing file with the same name. Perhaps you want to check that there isn’t a file by that name. Perhaps you need to know how old a given file is. Or perhaps you want to go through a list of files to find which ones are larger than a certain number of bytes and have not been accessed for a certain amount of time. Perl has a complete set of tests you can use to find out information about files.

File Test Operators

Perl has a set of file test operators that let you get particular information about files. They all take the form of -X, where the X represents the particular test (and there is a literal -X file test operator too, to confuse things a bit). In most cases, these operators return true or false. Although we call these things operators, you’ll find their documentation in perlfunc.

Note

To get the list, use the command line perldoc -f -X. That -X is literal and not a command-line switch. It stands in for all the file test operators since you can’t use perldoc to look them up individually.

Before you start a program that creates a new file, you might want to ensure that the file doesn’t already exist so that you don’t accidentally overwrite a vital spreadsheet data file or that important birthday calendar. For this, you can use the -e file test, testing a filename for existence:

die "Oops! A file called '$filename' already exists.\n" if -e $filename; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Perl One-Liners

Perl One-Liners

Peteris Krumins
Learning Perl, 8th Edition

Learning Perl, 8th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Programming Perl, 4th Edition

Programming Perl, 4th Edition

Tom Christiansen, brian d foy, Larry Wall, Jon Orwant

Publisher Resources

ISBN: 9781491954317Errata Page