我有一个工作代码来进行函数调用,但它是硬编码的。我需要通过循环使它变得动态。
function preorder(tree, node, res, child) {
if (node == "")
return
res[res["count"]++] = node
split(tree[node], child, ",")
#This must be made dynamic through looping
#based on number of childs from the elements of the array
preorder(tree,child[1],res)
preorder(tree,child[2],res)
preorder(tree,child[3],res)
}
BEGIN {
tree["1"] = "2,3"
tree["2"] = "4"
tree["3"] = "5"
tree["4"] = "6,7"
tree["5"] = "8,9"
tree["6"] = "10,11,12"
preorder(tree,"1",result)
printf "Child:\n"
for (n = 0; n < result["count"]; n += 1)
{
printf "\t"
printf result[n]" "
printf "\n"
}
printf "\n"
delete result
}
在上面的代码中,假设我在名为tree(tree["6"] = "10,11,12"
)的数组中的元素6中有3个逗号分隔值,preorder函数必须遍历它并为每个值执行自递归。
preorder(tree,child[1],res)
preorder(tree,child[2],res)
preorder(tree,child[3],res)
必须是动态的。
for (value in splitrecords)
preorder(tree,child[value],res)
我是AWK的初学者。有什么帮助吗?
答案 0 :(得分:1)
split()的第3个arg是正则表达式,而不是字符串,因此请使用regexp分隔符。这就是你想要的:
function preorder(tree, node, res, child, i) {
...
split(tree[node], child, /,/)
for (i=1; i in child; i++) {
preorder(tree,child[i],res)
}
...
}
答案 1 :(得分:1)
我重写了一些细微的变化,仍有一些事情困扰我但找不到更好的解决方案
function preorder(node, child, t, n) {
result[c++] = node
if(!(node in tree)) return
n=split(tree[node], child, ",")
for(t=1;t<=n;t++) preorder(child[t])
}
BEGIN {
tree[1] = "2,3"
tree[2] = "4"
tree[3] = "5"
tree[4] = "6,7"
tree[5] = "8,9"
tree[6] = "10,11,12"
preorder(1)
print "Child:"
for (n=0; n<c; n++) print "\t" result[n]
}