加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 给定/何时存在什么样的整洁用例?

发布时间:2020-12-15 22:00:53 所属栏目:大数据 来源:网络整理
导读:Perl 5.10引入了一个适当的开关结构,给定/何时,它似乎是一个强大的工具. 目前,perldoc perlsyn缺乏一些很好的例子. 最近发现的一个案例是使用文件测试运算符: given (-d "foo/bar/") { when (1) { ... } # defined is wrong as -d returns '' on a file. de
Perl 5.10引入了一个适当的开关结构,给定/何时,它似乎是一个强大的工具.

目前,perldoc perlsyn缺乏一些很好的例子.

最近发现的一个案例是使用文件测试运算符:

given (-d "foo/bar/") {
    when (1) { ... } # defined is wrong as -d returns '' on a file.
    default { ... }
}

或者:

given ("foo/bar/") {
    when (-d) { ... }
    default { ... }
}

对于我来说,特别是第一个版本看起来比一个if-else结构还是使用三元运算符,当依赖于测试的结果时,我需要在这两种情况下执行操作.

这让我想知道,除了简单的情况下,如果掉到智能匹配和避免超越if-elsif-elsif -… else结构,还有什么看起来整齐吗?

我有一个希望,给予/什么时候可以聪明,而不失去清晰度,但我没有任何好的例子.

有一件令我吃惊的事情是,你可以嵌套这个结构:

given ($filename) {
        when (-e) {
                when (-f) {
                        when (-z) { say "Empty file" }
                        default { say "Nonempty file" }
                }
                when (-d) {
                        when (-o) { say "Directory owned by me"}
                        default { say "Directory owned by someone else" }
                }
                default { say "Special" }
        }
        default { say "No such file or directory" } }

解决方法

在 recent answer到Zaid的问题 Strategies to handle a file with multiple fixed formats中,我结束了一个可怜的人的yacc,其主循环搜索了一系列正则表达式进行了第一场比赛:
while (<>) {
  given($_) {
    when (@{[ map $pattern{$_},@expect ]}) {}
    default {
      die "$0: line $.: expected " . join("|" => @expect) . "; gotn$_";
    }
  }
}

在另一个问题中,David B wanted to match against multiple regexes和my answer uses smart matching隐含地循环使用正则表达式:

#! /usr/bin/perl

use warnings;
use strict;

use feature 'switch';

my @patterns = (
  qr/foo/,qr/bar/,qr/baz/,);

for (qw/ blurfl bar quux foo baz /) {
  print "$_: ";
  given ($_) {
    when (@patterns) {
      print "hit!n";
    }
    default {
      print "miss.n";
    }
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读