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.
perlservices.at is a B2B service provider for Perl in Vienna, Austria. I'm a professional software developer since 1989 and a Perl specialist since 1998. I also like Go (囲碁), Japanese and Korean culture and language.
Leave a comment