生成包含条件项的列表

Generate list with conditional items

是否可以创建包含条件项的数组?

my @a = (1, ($condition) ? 2 : "no-op", 3);

这样 "no-op" 是这样工作的函数,如果 $condition 为假,那么我得到列表 (1, 3) 但如果 $condition 为真,我得到 (1, 2, 3) ?


背景:

use strict;
use warnings;
use File::Find::Rule;

my $rule = File::Find::Rule->new();
$rule->or(
    $rule->new->name('*.cfg')->prune->discard,
    $rule->directory->name("_private.d")->prune->discard,
    $rule->new->name('*.t')->prune->discard,
    $rule->new->name('*.bak')->prune->discard,
    $rule->new->name('.*.bak')->prune->discard,
    $rule->new->name('.#*')->prune->discard,
);

my @files = $rule->in(".");

在某些情况下,我想包含行

$rule->directory->name("_private.d")->prune->discard

在其他情况下,我不想排除目录 _private.d..

您可以使用空列表 () 跳过第二个元素,

my @a = (1, ($condition ? 2 : ()), 3);

一般来说,您可以使用

提高可读性
my @a;
push @a, 1;
push @a, 2 if $condition;
push @a, 3;

在上下文中,那将是

my @rules;
push @rules, $rule->new->name('*.cfg')->prune->discard;
push @rules, $rule->directory->name("_private.d")->prune->discard if $condition;
push @rules, $rule->new->name('*.t')->prune->discard;
push @rules, $rule->new->name('*.bak')->prune->discard;
push @rules, $rule->new->name('.*.bak')->prune->discard;
push @rules, $rule->new->name('.#*')->prune->discard;

my $rule = File::Find::Rule->new()->or(@rules);
my @files = $rule->in(".");