开发者

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) {}
 开发者_JAVA百科 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. ;-)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜