3 ms·
Reminds me on bash, where I also have to prefix values to compare with x, to be able to handle empty vars. if [ x$1 == x$2 ]; But automatic string to floa
by rurban 12y ago
Reminds me on bash, where I also have to prefix values to compare with x, to be able to handle empty vars.
if [ x$1 == x$2 ];
But automatic string to float conversion is just crazy, esp. in comparison context. Perl, which is equally soft, has at least numerical and string comparison operators.
$ perl -e'print "0e462097431906509019562988736854" ==
"0e830400451993494058024219903391"'
1
$ perl -e'print "0e462097431906509019562988736854" eq
"0e830400451993494058024219903391"'
So the solution is to use === which does not compare references with strings but the values, or the strcmp function. And refrain from using == with strings at all.
'0XAB' == '0xab' is true.
Comparing any string to 0 with == will return true.
- viraptor 12y agoI'm not sure why does this crazy "x" prefix tale still continue. You can simply quote them instead. Especially if you use bash and not some other sh-compatible shell: if [ "$1" == "$2" ]; will work just fine. If you need all sh compatibility, it should be test for "x$1" anyway (still quoted).
- Arkanosis 12y agoI think you meant “=”, not “==” (though the latter would work with bash).
- viraptor 12y agoWell, either in the example. Parent was saying "Reminds me on bash" For sh version, I'd go with super-safe: if test "x$1" = "x$2"
- seanp2k2 12y agoIf you're doing that, even better to use "x${1}" to be safer. Also, conditional expressions ( [[ instead of [ or `test`) are generally a bit more well-behaved. See http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression http://wiki.bash-hackers.org/syntax/ccmd/conditional_express... for more info.
- viraptor 12y agoBut [[ is a bashism - it won't work on bare sh.
- Arkanosis 12y agoActually, you don't prefix with “x” to handle empty vars, but special characters, as Stephane Chazelas recently reminded: http://www.zsh.org/mla/workers/2015/msg00797.html http://www.zsh.org/mla/workers/2015/msg00797.html
- seanp2k2 12y agoAgain here conditional expressions should make this a non-issue ( [[ instead of [ ) since the stuff inside doesn't get parsed the same as general input. See http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression http://wiki.bash-hackers.org/syntax/ccmd/conditional_express...
- Arkanosis 12y agoYes, but then you need either bash or zsh. It won't work on bare sh (or on dash, which is the default /bin/sh on Debian and derivatives like Ubuntu).