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:
use strict; use warnings;
at the beginning. It’s also good practice to use the 3-argument form of open, and to test for failure:
my $file = 'C:/Work/PAYROLL>TXT'; open(my $fh, '<', $file) or die "Cannot open file '$file' for reading: + $!";
Update: The range operator, i.e. .. used in scalar context, is useful for this kind of problem:
#! perl use strict; use warnings; my $start_day = '1/17'; while (my $payperiod = <DATA>) { if ($payperiod =~ /$start_day/ .. 0) { print $., ' '. $payperiod; } } __DATA__ start: 1/3 aaa end: 1/16 start: 1/17 bbb end: 1/30 start: 1/31 ccc end: 2/13
Output:
1:26 >perl 1110_SoPW.pl 4 start: 1/17 5 bbb 6 end: 1/30 7 start: 1/31 8 ccc 9 end: 2/13 1:26 >
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,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: why does typo work?
by Athanasius
in thread why does typo work?
by ggadd
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |