查找在Perl中的大字符串中找到子字符串的行号

Sky*_*eSM 2 perl substring line

在perl字符串中搜索子字符串的行号的最佳方法是什么?例如:搜索"逃脱"

"How to Format
? put returns between paragraphs
? for linebreak add 2 spaces at end
? _italic_ or **bold**
? indent code by 4 spaces
? backtick escapes `like _so_`
? quote by placing > at start of line
? to make links
<http://foo.com>
[foo](http://foo.com)"
Run Code Online (Sandbox Code Playgroud)

应该给6作为行号.

cjm*_*cjm 5

我是这样做的:

my $string = 'How to Format
- put returns between paragraphs
- for linebreak add 2 spaces at end
- _italic_ or **bold**
- indent code by 4 spaces
- backtick escapes `like _so_`
- quote by placing > at start of line
- to make links
<http://foo.com>
[foo](http://foo.com)';

if ($string =~ /escape/) {
  # Count the number of newlines before the match.
  # Add 1 to make the first line 1 instead of 0.
  my $line = 1 + substr($string, 0, $-[0]) =~ tr/\n//;

  print "found at line $line\n";
}
Run Code Online (Sandbox Code Playgroud)

除非实际找到字符串,否则这可以避免计数行进行任何计算.它使用@-变量来找出匹配开始的位置,然后用于tr计算换行符.


Sea*_*ean 5

想到另一个解决方案.在最近的Perls中,您可以在字符串上打开文件句柄,然后使用特殊$.变量自动跟踪行号:

open my $handle, '<', \$str;
my $linenum;

while (<$handle>) {
    $linenum = $., last if /escape/;
}

close $handle;

if (defined $linenum) {
    print "Found match on line $linenum\n";
} else {
    print "No match found\n";
}
Run Code Online (Sandbox Code Playgroud)