You've got an error in testing for your $linenum. Also, you're incrementing your variable after you test and loop back, so it never gets incremented. Change
next unless ($linenum = $lastline);
to
next unless ($linenum++ >= $lastline);
Update: sorry, I didn't do this carefully enough, changed to work
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan