Think about Loose Coupling | |
PerlMonks |
Re: why does typo work?by Athanasius (Archbishop) |
on Jan 04, 2015 at 14:58 UTC ( [id://1112111]=note: print w/replies, xml ) | Need Help?? |
Hello ggadd, and welcome to the Monastery! The test if ($. >= $num), which is what you meant to write, actually makes no sense, because it is comparing two things which are unrelated, a line number and a date. But the typo, if ($. => $num), evaluates to $num, because => is a form of the comma operator: Binary "," is the comma operator. In scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. This is just like C's comma operator. (perlop#Comma-Operator) Now, $num is initially undef, which it remains until $payperiod =~ /$start_day/ evaluates to true (i.e., the start day is found), at which point it is set to $., the current line number of the filehandle $fh (the last filehandle accessed). Since line numbers start at one, $num is now a positive integer greater than zero. So before the start date is found, the if condition evaluates to undef, which is false, and nothing is printed. But once the start date has been found, the if condition evaluates to a non-zero integer, which is true, and each line is printed from that point on. Incidentally, your script would benefit greatly from the addition of:
at the beginning. It’s also good practice to use the 3-argument form of open, and to test for failure:
Update: The range operator, i.e. .. used in scalar context, is useful for this kind of problem:
Output:
There is an efficiency gain to using the range operator: “The right operand is not evaluated while the operator is in the "false" state, and the left operand is not evaluated while the operator is in the "true" state.” Hope that helps,
In Section
Seekers of Perl Wisdom
|
|