检测可选函数参数(标量)


8

考虑以下脚本:

function alfa(bravo, charlie) {
  if (charlie)
    return "charlie good"
  else {
    return "charlie bad"
  }
}
BEGIN {
  print alfa(1, 1)
  print alfa(1, 0)
  print alfa(1, "")
  print alfa(1)
}

结果:

charlie good
charlie bad
charlie bad
charlie bad

Awk是否可以告诉何时未提供参数?

Answers:


6

是的,您可以这样做:

function alfa(bravo, charlie) {  
  if (charlie) {
    return "charlie good"
  }
  if (charlie == 0 && charlie == "") {
    return "charlie not provided"
  }
  if (!charlie && charlie != 0) {
    return "charlie null"
  }
  if (!charlie && charlie != "") {
    return "charlie 0"
  }
}

结果:

charlie good
charlie 0
charlie null
charlie not provided

6

awk没有内置的方法来检查变量是否已初始化。您必须自己做:

function alfa(bravo, charlie) {
  if (charlie == 0 && !length(charlie))
    return "charlie bad"
  else {
    return "charlie good"
  }
}
BEGIN {
  print alfa(1, 1)
  print alfa(1, 0)
  print alfa(1, "")
  print alfa(1)
}

通用方式:

var == 0 && !length(var)

未初始化的变量0导致var == 0计算结果为true,!length(var)排除了时的情况var = 0

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.