One-liner to count the number of lines in a file

There is a cute Perl one-liner to count the number of lines in a file:

perl -nE'}{say$.' foo.txt

Let's see how perl parses this one-liner:

$ perl -MO=Deparse -nE'}{say$.' foo.txt 
BEGIN {
    $^H{'feature_unicode'} = q(1);
    $^H{'feature_say'} = q(1);
    $^H{'feature_state'} = q(1);
    $^H{'feature_switch'} = q(1);
}
LINE: while (defined($_ = <ARGV>)) {
    ();
}
{
    say $.;
}
-e syntax OK

So -E turns on the special features (we only use say here) and -n provides the boilerplate code. As for $., perldoc perlvar says that it is the current line number for the last filehandle accessed.

Leave a comment

About hanekomu

user-pic