Generate list with conditional items

后端 未结 2 513
臣服心动
臣服心动 2021-01-22 06:40

Is it possible to create an array with conditional items?

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

Such that \"no-op\" is fu

相关标签:
2条回答
  • 2021-01-22 07:10

    You can use empty list () to skip second element,

    my @a = (1, ($condition ? 2 : ()), 3);
    
    0 讨论(0)
  • 2021-01-22 07:12

    Generally speaking, you can get some readability gains using

    my @a;
    push @a, 1;
    push @a, 2 if $condition;
    push @a, 3;
    

    In context, that would be

    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(".");
    
    0 讨论(0)
提交回复
热议问题