Name

Yet Another Perl 6 Operator: Filetests?

Version

Maintainer: Adriano Ferreira <ferreira@cpan.org>
Date: 03 Jan 2008
Last Modified: 03 Jan 2008
Number: 18
Version: 2
Status: Draft

Body

This article is not about some set of Perl 6 operators, but rather about what happened to Perl 5 filetests operators. Short answer: They are not operators anymore.

Where programmers were used to write

# good ol' Perl 5
if ( -e $filename ) { print "exists\n" }

they will now use pair methods that may be expressed as methods or smart patterns.

if $filename.:e { say "exists" }
# or
if $filename ~~ :e { say "exists" }

As filetests are now methods, the $filename object's class now decides how to dispatch pair methods. It just happens that Str (filenames), IO (filehandles), and Statbuf (stat buffers) default to the expected filetest semantics.

With the pattern form, multiple tests as adverbial pairs can be stacked into one term, so they are ANDed together. Thus

when :r :w :x 

tests whether the current topic is readable, writeable and executable.

The advantage of the method form may be seen in examples like sorting an array of files by modification time.

sort { $^a.:M <=> $^b.:M }, @files
# or better/shorter
sort { .:M }, @files

All Perl 5 filetest operators are listed in perlfunc.pod which will likely be supported in Perl 6 as well. However negated tests become easier with the negated adverbial forms like

when :!s    # file has zero size (same as :z)
when :!t    # not a tty

The filetests do not return stat buffers, but simple scalars of type Bool, Int, or Num. The stat buffer will be automatically reused if the same object has recently been queried. ("Recently" is defined here as less than a second or so.) If this is a concern, an explicit stat() or lstat() may be used to return an explicit stat buffer which is not subject to timeout. These objects can be tested repeatedly just as filenames and handles can.

In the recently released Perl 5.10, file test operators can be stacked too. So -f -w -x $file is equivalent to -x $file && -w _ && -f _. That syntactical addition was inspired by early Perl 6 design ideas and is related to how Perl 5 caches the stat buffer into _. In turn, the Perl 6 counterpart is based on transparent reuse of the stat buffer and combination via junctions.

See Also

The coming articles on smart matching.

The soon-to-be article on junction operators.

$Revision: 135 $