Reputation: 40748
Is it possible to create an array with conditional items?
my @a = (1, ($condition) ? 2 : "no-op", 3);
Such that "no-op"
is function that works such that if $condition
is false, then I get the list (1, 3)
but if $condition
is true, I get (1, 2, 3)
?
Background:
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(".");
In some cases I would like to include the line
$rule->directory->name("_private.d")->prune->discard
and in other cases I would not like to exclude directory _private.d
..
Upvotes: 2
Views: 122
Reputation: 385734
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(".");
Upvotes: 2
Reputation: 50637
You can use empty list ()
to skip second element,
my @a = (1, ($condition ? 2 : ()), 3);
Upvotes: 6