[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [bug-gawk] Variable issue substr
From: |
Aharon Robbins |
Subject: |
Re: [bug-gawk] Variable issue substr |
Date: |
Thu, 14 May 2015 15:40:41 +0300 |
User-agent: |
Heirloom mailx 12.5 6/20/10 |
Hi.
> Sorry for HTML.
> Thank you. This hack with adding zero works fine.
> But I really can't understand the root cause of problem.
> When b1=9, in loop condition this variable converting to number.
> So there must be i<=9. Why does i going out of the range?
OK, here's your original program:
BEGIN {
a = "2345"
b = "6789"
a1 = substr(a, length(a), 1)
b1 = substr(b, length(b), 1)
print a1, b1
for (i = a1; i <= b1; i++) {
print i
}
}
Let's think about what's going on. a1 and b1 are both strings.
NOT numbers. When `i = a1' is done, i also becomes a string. The loop
body prints i.
Then we hit i++. Now it gets interesting. i is converted to a number
and incremented. The new numeric value is then converted back to a string
for the comparison with b1.
The comparison is <=, so when i hits 9, "9" <= "9" is true, and the loop
continues. When i hits 10, it's converted to "10", and "10" <= "9" is
also true (*string* comparison), so the loop continues until i hits 90,
at which point "90" <= "9" is no longer true, and the loop terminates.
Hope this helps,
Arnold