Detect optional function argument (scalar)
Yes, you can do this:
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"
}
}
Result:
charlie good
charlie 0
charlie null
charlie not provided
awk
doesn't have a builtin way to check variable had been initialized. You must do it yourself:
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)
}
The general way:
var == 0 && !length(var)
An uninitialized variable and 0 causes var == 0
to be evaluated to true, !length(var)
excludes the case when var = 0
.