Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Overriding "-s", "-f" and other -X functions

by Doctrin (Beadle)
on Jul 07, 2018 at 07:38 UTC ( #1218081=perlquestion: print w/replies, xml ) Need Help??
Doctrin has asked for the wisdom of the Perl Monks concerning the following question:

Hello dear Monks! I know that one can override built-in Perl functions via something like
BEGIN { *CORE::GLOBAL::open = sub { warn "Captured: " . $_[1]; open $_[0], $_ +[1] }; }
Is there a way to override "-X" functions (-s,-d,-f...) similarly? Thanks!

Replies are listed 'Best First'.
Re: Overriding "-s", "-f" and other -X functions
by haukex (Canon) on Jul 07, 2018 at 07:55 UTC
Re: Overriding "-s", "-f" and other -X functions
by Athanasius (Bishop) on Jul 07, 2018 at 07:53 UTC

    Hello Doctrin,

    I haven’t tried it, but here is an excerpt from the documentation for the core overload pragma, under “Overloadable Operations”:

    • File tests

      The key '-X' is used to specify a subroutine to handle all the filetest operators (-f, -x, and so on: see -X for the full list); it is not possible to overload any filetest operator individually. To distinguish them, the letter following the '-' is passed as the second argument (that is, in the slot that for binary operators is used to pass the second operand).

      Calling an overloaded filetest operator does not affect the stat value associated with the special filehandle _. It still refers to the result of the last stat, lstat or unoverloaded filetest.

      This overload was introduced in Perl 5.12.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Note that this only works if the thing that you're calling the -X on is an object of the overloaded class.

      use warnings; use strict; { package Foo; use Data::Dump; use overload fallback=>0, '-X' => sub { dd @_; return 1 }; } my $foo = bless {}, 'Foo'; print -e $foo ? 'yes' : 'no', "\n"; my $bar = "doesnotexist"; print -e $bar ? 'yes' : 'no', "\n"; __END__ (bless({}, "Foo"), "e", "") yes no

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1218081]
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2018-12-13 04:15 GMT
Find Nodes?
    Voting Booth?
    How many stories does it take before you've heard them all?

    Results (61 votes). Check out past polls.