Pablo Marin-Garcia
Pablo Marin-Garcia

Reputation: 4251

Do file tests use `$_` or `_` in a given…when switch?

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. ;-)

Upvotes: 3

Views: 189

Answers (2)

brian d foy
brian d foy

Reputation: 132773

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.

Upvotes: 0

Axeman
Axeman

Reputation: 29854

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.

Upvotes: 5

Related Questions