3 ms·
I used AWK for many years, but one day I realized that I had pushed AWK beyond whats its meant for, same as the author here. classic red flag from the article:
by 2h 4y ago
I used AWK for many years, but one day I realized that I had pushed AWK beyond whats its meant for, same as the author here. classic red flag from the article:
function NUMBER( res) {
return (tryParse1("-", res) || 1) &&
(tryParse1("0", res) || tryParse1("123456789", res) && (tryParseDigits(res)||1)) &&
(tryParse1(".", res) ? tryParseDigits(res) : 1) &&
(tryParse1("eE", res) ? (tryParse1("-+",res)||1) && tryParseDigits(res) : 1) &&
asm("number") && asm(res[0])
}
why put yourself through this, when you can just do something like this instead:
package parse
import "strconv"
func parse_float(s string) (float64, error) {
return strconv.ParseFloat(s, 64)
}
func parse_int(s string) (int64, error) {
return strconv.ParseInt(s, 10, 64)
}
- pmarreck 4y agoDepends on the AWK implementation, apparently. bash> awk -v v="80.1%" 'BEGIN{print v+0.1}' 80.2 gawk has `strtonum`. But yes, parsing in awk generally looks like a pain. With plain positive/negative ints though, not so hard: echo "123456" | awk '{ if ($0 ~ /^-?[0-9]+$/) { num = 0 sign = 1 start = 1 if (substr($0, 1, 1) == "-") { sign = -1 start = 2 } for (i = start; i <= length($0); i++) { digit = substr($0, i, 1) num = num * 10 + digit } num = sign * num print "The integer is:", num } else { print "Invalid input string:", $0 } }'
- donio 4y agoNot disagreeing with the overall point but that particular example is from an AWK JSON parser implementation so the whole point is to do it in AWK. If you look at the entire file it's not too bad considering. Funnily the actual Go JSON decoder code ends up doing something similar during scanning: https://github.com/golang/go/blob/master/src/encoding/json/decode.go#L330 https://github.com/golang/go/blob/master/src/encoding/json/d...
- czx4f4bd 4y agoAs mentioned, the example you quoted is from a pure-AWK JSON parser. I don't dispute that AWK has issues, but AWK is one of those languages that magically coerces strings to numbers, so you can just write `"1" + 2 + "3.5"` and it'll work.