Why we can not use “le” in for loop and can use in “if condition”
I've made this program as a beginner. Need to clarify something! Why I m not able to use "le" in a for loop given below but I'm able to use it in "if condition". What is the reason behind that. ?
print "Type the number upto series should run\n"; my $var; $var = int<STDIN>; chomp $var; my ($i, $t); my $x = 0; my $y = 1; if($var eq 1) { print "\nYour Series is : $x\n"; } elsif($var eq 2){ print "\nYour Series is : $x $y\n"; } elsif($var ge 2) { print "Your Series is : $x $y "; for($i = 1; $i le $var - 2; $i++) { # Why the condition not working when I'm using "le" # but it does work when I'm using "<=" $t = $x + $y; $x = $y; $y = $t; print "$t "; } print "\n"; } else { print "Error: Enter a valid postive integer\n"; }
Answers
You are free to use le and <= as you like. But you should be aware that they are completely different operators.
Numeric comparision operators are
== != < <= > >= <=>
The equivalent string comparision operators are
eq ne lt le gt ge cmp
Strings and numbers are converted to each other as needed. This means for example that
3 ge 20 # true: 3 is string-greater than 20 11 le 2 # true: 11 is string-less-or-equal than 2
because lexicographic ordering compares character by character. Using the numeric operators when you want to treat the contents of your $variables as numbers is therefore preferable and will yield the correct results.
Note that Perl translates between strings and numbers invisibly. It is advisable to use warnings, so that you get a helpful message when a string can't represent a number (e.g. "a").