PowerShell strings, ints and comparisons
I hit this doing a little bit of playing around over the weekend, porting some old BASIC progams into PowerShell.
Most of the time treating strings of digits as numbers "just works":
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>$line = "5, 22.5" | |
>$bits = $line.split(",") | |
>$bits | |
5 | |
22.5 | |
>$ratio = $bits[1]/$bits[0] | |
>$ratio | |
4.5 | |
>write-host ($bits[0] -eq 5) | |
True |
but at times it all goes horribly wrong
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>write-host ($bits[0] -gt 30) | |
True | |
>write-host ($bits[0] -gt 60) | |
False | |
>write-host ($bits[0] -gt 50) | |
False | |
>write-host ($bits[0] -gt 49) | |
True | |
>write-host ($bits[0] -eq 50) | |
False |
with the ASCII value of '5' being 53, we see that these comparisons are being done lexically.
What is needed in these circumstances is an explicit coercion some place down the line; like:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>write-host ([int]$bits[0] -gt 45) | |
False |
No comments :
Post a Comment