Iterators - expressions tha change each time you call them
Archive - Originally posted on "The Horse's Mouth" - 2006-04-27 06:21:54 - Graham EllisIf you're programming and you write the same expression into your code twice without changing any of the variables, you're simply writing the same expression twice, right? For example, here's a piece of Perl code that exits if $userval is 0, but adds it in to a total and keep going if it's not zero.
if ($userval == 0) {
print "job done\n";
exit;
}
$total += $userval;
If you're reading from a file, though, things are different. Refer to the same file handle twice, and you'll get the next line read in each time - thus:
if (<FH> == 0) {
print "job done\n";
exit;
}
$total += <FH>;
will read from a file handle TWICE - if the first line read is zero, the program exits. If the first line was NOT zero, a second line is read and that value in that line is added to $total.
Why the difference? Because the read from operator - <> in Perl - is what we call an iterator, and each time we refer to it, it moves on to the next value.
This one often catches new programmers ... the solution is to read the value just once and save it into a variable - thus:
$userval = <FH>;
if ($userval == 0) {
print "job done\n";
exit;
}
$total += $userval;