3

When using file test operators, the stat() results are cached in _ so if you want to perform several tests you don't need to do more system calls.

if (-f $file_) {
  say 'readable' if -r _;
  say 'writable' if -w _;
}

If I use them in a given…when, do they use _ or $_?

given ($file) {
  when (! -f) {}
  when (-r) {say 'readable';continue}
  when (-w) {say 'writable';continue}
  ....
}

I have the impression that this will use $_. Is that true? Also because given…when does not have default fall-through it is necessary to use continue in order to see other matches.

Probably this case is better resolved with ifs and uses less typing than with the given…when approach. But it is too tempting to see if you can fit given…when when refactoring your software. ;-)

2 Answers 2

5

This is what it deparsed into:

sub {
    use warnings;
    use strict 'refs';
    BEGIN {
        $^H{'feature_unicode'} = q(1);
        $^H{'feature_say'} = q(1);
        $^H{'feature_state'} = q(1);
        $^H{'feature_switch'} = q(1);
    }
    my $file = shift @_;
    given ($file) {
        when (not -f $_) {
            ();
        }
        when (-r $_) {
            say 'readable';
            continue;
        }
        when (-w $_) {
            say 'writable';
            continue;
        }
    }
}

So it doesn't show smart matching in the op codes.

1
  • silly me, obviously not! my focus was on $_ vs _ and I was not paying attention and put the ~~ because is the default test method for when, but here the test is the -r etc itself not ~~. I am editing the question removing the ~~ Mar 30, 2011 at 23:06
0

The virtual filehandle _ is never the default argument for a file test operator (not counting the stacked file tests that all operate of the same file, since only one of them has an argument). You have to use it explicitly to tell the file test to use the values from the last file stat.

$_ is the default for most of the other file test operators, but not all of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.