Home arrow Perl Programming arrow Page 2 - File Tests in Perl

File Test Operators - Perl

In this article, you will learn how to find out useful information about files in Perl. It is excerpted from chapter 11 of the book Learning Perl, Fourth Edition, written by Randal L. Schwartz, Tom Phoenix and brian d foy (O'Reilly; ISBN: 0596101058). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

  1. File Tests in Perl
  2. File Test Operators
  3. The stat and lstat Functions
  4. The localtime Function
  5. Bitwise Operators
  6. Using the Special Underscore Filehandle
By: O'Reilly Media
Rating: starstarstarstarstar / 22
May 10, 2007

print this article



Don’t worry if you don’t know what some of the other file tests mean—if you’ve never heard of them, you won’t be needing them. But if you’re curious, get a good book about programming for Unix. (On non-Unix systems, these tests all try to give results analogous to what they do on Unix, or give undef for an unavailable feature. Usually, you’ll be able to guess what they’ll do.)

If you omit the filename or filehandle parameter to a file test (that is, if you have-ror just-s), the default operand is the file named in$_.* So, to test a list of filenames to see which ones are readable, you type the following:

  foreach (@lots_of_filenames) {
print "$_ is readable\n" if -r; # same as -r $_

But if you omit the parameter, be careful that whatever follows the file test doesn’t look like it could be a parameter. For example, if you wanted to find out the size of a file in KB rather than in bytes, you might be tempted to divide the result of-sby1000(or1024), like this:

  # The filename is in $_
  my $size_in_K = -s / 1000; # Oops!

When the Perl parser sees the slash, it doesn’t think about division. Since it’s looking for the optional operand for-s, it sees what looks like the start of a regular expression in forward slashes. To prevent this confusion, put parentheses around the file test:

  my $size_in_k = (-s) / 1024; # Uses $_ by default

Explicitly giving a file test a parameter is safer.

>>> More Perl Programming Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: