[ABE.pm] perl 5.10 rules! - stackable -X operators

Ricardo SIGNES rjbs-perl-abe at lists.manxome.org
Fri Jun 8 14:25:55 PDT 2007


Unix has this program, test(1), which lets you construct simple boolean
statements by running a standard unix command that takes weird arguments.  It's
really clever, and has helped define a lot of conventions.  Some of them are
enshrined in the "-X" function in perl.  You can say, for example:

  if (-f $file) {
    unlink $file or die "couldn't unlink file: $!";
  }

...and you know that the unlink will only happen if $file is a plain file (it
can contain a filename or filehandle).  That is: it's not a directory, pipe,
fifo, or other weird thing.

Of course, now you'll find that sometimes it fails because you don't have write
access to the file.  So, you write:

  if (-f $file and -w $file) {
    unlink $file or die "couldn't unlink file: $!";
  }

And actually, you only want to delete empty files:

  if (-f $file and -w $file and -z $file) {
    unlink $file or die "couldn't unlink file: $!";
  }

Well, blech.  That's ugly.  Of course, some of you may now be thinking: "But I
can just write this:

  if (-f $file and -w _ and -z _) {
    unlink $file or die "couldn't unlink file: $!";
  }

That's true.  Of course, I still says blech, because in 5.10, you can write:

  if (-f -w -z $file) {
    unlink $file or die "couldn't unlink file: $!";
  }

Clearer *and* shorter!  Is there anything more Perlish than that combination?
(That was a rhetorical question.)

-- 
rjbs


More information about the ABE-pm mailing list