2
php -R '$count++' -E 'print "$count\n";' < somefile

will print the number of lines in 'somefile' (not that I would actually do this).

I'm looking to emulate the -E switch in a perl command.

perl -ne '$count++' -???? 'print "$count\n"' somefile

Is it possible?

3 Answers3

10

TIMTOWTDI

You can use the Eskimo Kiss operator:

perl -nwE '}{ say $.' somefile 

This operator is less magical than one thinks, as seen if we deparse the one-liner:

$ perl -MO=Deparse -nwE '}{say $.' somefile 
BEGIN { $^W = 1; }
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

It simply tacks on an extra set of curly braces, making the following code wind up outside the implicit while loop.

Or you can check for end of file.

perl -nwE 'eof and say $.' somefile

With multiple files, you get a cumulative sum printed for each of them.

perl -nwE 'eof and say $.' somefile somefile somefile
10
20
30

You can close the file handle to get a non-cumulative count:

perl -nwE 'if (eof) { say $.; close ARGV }' somefile somefile somefile
10
10
10
Community
  • 1
  • 1
TLP
  • 66,756
  • 10
  • 92
  • 149
  • @Zaid It's a nice trick, thanks for sharing it. I just realised it will not actually work with the `-p` switch, like it says in the question I linked to - only `-n`. With `-p` it will become `while (<>) { (); } { code } continue { print }`. – TLP Feb 01 '12 at 16:57
6

This should be what you're looking for:

perl -nle 'END { print $. }'  notes.txt
Sebastian Stumpf
  • 2,761
  • 1
  • 26
  • 34
6

You can use an END { ... } block to add code that should be executed after the loop:

perl -ne '$count++; END { print "$count\n"; }' somefile

You can also easily put it in its own -e argument, if you want it more separated:

perl -ne '$count++;' -e 'END { print "$count\n"; }' somefile

See also:

Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118