Perl中的"grep -n"相当于什么?

Man*_*nde 2 perl

我想用行号来说一句话.使用命令grep -n或在shell中很容易实现sed.Perl中是否有可用的等价物?我检查了grep函数,但是我无法找到我需要的东西.

Dav*_*oss 12

在名为mygrep的文件中:

#!/usr/bin/perl

use strict;
use warnings;

my $match = shift;

while (<>) {
  if (/\Q$match/) {
    print "$. : $_";
  }
}
Run Code Online (Sandbox Code Playgroud)

然后从命令行:

$ ./mygrep if mygrep 
6 : my $match = shift;
9 :   if (/\Q$match/) {
Run Code Online (Sandbox Code Playgroud)

应该足以让你入门.

  • 将此作为脚本编写似乎有点过分.你可以轻松地做一个单行:perl -wne'print'$.:$ _"如果m /\Qmatch /' (3认同)
  • @William Pursell - 是的,但是@davorg写了一些东西,只是学习Perl的人会受益. (2认同)