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) . "; got\n$_";
- }
- }
- }
在另一个问题中,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";
- }
- }
- }