With these types of complex programs, it's better to let Perl generate the Perl code for you:
$ perl -MO=Deparse -pe'exit if $.>2'
Which will gladly tell you the answer,
LINE: while (defined($_ = <ARGV>)) {
exit if $. > 2;
}
continue {
die "-p destination: $!\n" unless print $_;
}
Alternatively, you can simply run it as such from the command line,
$ perl -pe'exit if$.>2' file.txt