根据条件建立傀儡变量

根据条件建立傀儡变量

所以我正在适应 puppet 中的不可变变量,现在寻求一些建议,或者澄清我是否已经走在正确的轨道上。

我有一个想要同步的目录,但可能还有其中的多个子目录。因此,我想建立一个包含一个或多个路径的数组,以传递给递归文件资源。理想情况下,我会有这样的

$paths = ['fist/path'] # assume this is provided via class parameter
# this should work, since it's only overriding what was provided from higher scope
if($condition) {
  $paths += 'second/path'
}
# this won't fly, since $paths has already been set once locally
if($another_condition) {
  $paths += 'third/path'
}

但我不能这样做,因为变量是不可变的。到目前为止,我想到的“最佳”方法是这样的

$paths = ['fist/path']
if($condition) {
  $condition_1_path = ['second/path']
} else {
  $condition_1_path = []
}
if($another_condition) {
  $condition_2_path = ['third/path']
} else {
  $condition_2_path = []
}

$paths = concat($paths, $condition_1_path, $condition_2_path)

我不确定连接如果为其中一个参数提供了一个空数组,它将从结果中省略一个条目,但等待测试它弄清楚如何加载 stdlib

无论如何,在我看来,这段代码简直太丑陋了。有没有更简洁的方法来做这样的事情?

答案1

虽然很丑,但是我已经这样做了。

if($condition) {
  $condition_1_path = 'first/path'
} else {
  $condition_1_path = ''
}
if($another_condition) {
  $condition_2_path = 'second/path'
} else {
  $condition_2_path = ''
}

# split into array based on whitespace
$mylistofpaths = split("$condition_1_path $condition_2_path", '\s+')

相关内容