【问题标题】:Reading a text file in Perl, Searching for a Word, Returning Line Number [closed]在 Perl 中读取文本文件,搜索单词,返回行号 [关闭]
【发布时间】:2014-12-28 05:34:32
【问题描述】:

我正在尝试编写一段由某些 C 代码调用的代码,其中包含数据文件和作为参数传入的特定单词,并将行号输出到 stdout。我玩了一些 $substr ,但没有成功。

我认为最终会是这样的:

if ($oneLineofTheData !~ theSearchWord){
    counter++;
}
else{
    output counter to stdout
}

这会是更简单的处理方法吗?我将如何传递文件名和搜索词?我是 Perl 的新手,所以提前感谢您的帮助。

谢谢,

【问题讨论】:

    标签: string perl search file-io


    【解决方案1】:

    要将参数传递给 Perl 程序,请使用 @ARGV 数组。

    要检查字符串中是否存在子字符串,请使用index

    $. 保留上次访问的文件句柄的行号。

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my ($filename, $word) = @ARGV;
    
    open my $FH, '<', $filename or die $!;
    while (my $line = <$FH>) {
        if (-1 != index $line, $word) {
            print $.;
            exit
        }
    }
    

    【讨论】:

      【解决方案2】:

      把它放在一个名为whatever.pl的文件中:

      $ct=0;
      while(<>) {
        if ($_ =~ m/$ARGV[0]/) {
          print $ct;
          exit;
        }
        $ct++; 
      }
      

      然后在命令行运行:

      perl whatever.pl filename.txt wordToMatch
      

      【讨论】:

      • 您可以使用$. 而不是$ct 来缩短脚本。 $_ =~ m/$ARGV[0]/也可以缩写为m/$ARGV[0]/
      • 啊,很好的电话@RenéNyffenegger。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 2023-03-07
      • 2020-05-20
      • 1970-01-01
      相关资源
      最近更新 更多