Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Chapter 12. File Tests

Earlier, we showed how to open a filehandle for output. Normally, that will create 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 not 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

Before we start a program that creates a new file, let’s make sure that the file doesn’t already exist so that we don’t accidentally overwrite a vital spreadsheet datafile or that important birthday calendar. For this, we use the -e file test, testing a filename for existence:

die "Oops! A file called '$filename' already exists.\n"
  if -e $filename;

Notice that we don’t include $! in this die message, since we’re not reporting that the system refused a request in this case. Here’s an example of checking whether a file is being kept up-to-date. In this case, we’re testing an already opened filehandle, instead of a string filename. Let’s say that our program’s configuration file should be updated every week or two. (Maybe it’s checking for computer viruses, say.) If the file hasn’t been modified in the past 28 days, then something is wrong:

warn "Config file is looking pretty old!\n"
  if -M CONFIG > 28;

The third example is more complex. Here, let’s say that ...

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

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page