LoginSignup
4
4

More than 5 years have passed since last update.

ファイルの中にある特定文字列を数える(Perl版)

Posted at

Python - ファイルの中にある特定文字列を数える - Qiita
触発されて。

  • pythonみたいにcountメソッドは無いのでsplitで代用。
  • splitは分割数なので-1する。(マッチしない行でも1個の分割数)
  • splitでなくて正規表現の置換した数でもできそうだが、遅そう。
  • エラー処理は面倒だったので省略。
  • ファイルを丸呑みできるなら
match_count.pl
#!/usr/bin/perl
use strict;
use warnings;

sub count_words
{
  my ($stream, $search_word) = @_;
  my $num = 0;
  while (<$stream>) {
    my $match_num = scalar (my @list = split /$search_word/, $_) - 1;
    $num += $match_num;
  }
  return $num;
}

sub main
{
  if (-t) {
    my ($file, $search_word) = @ARGV;
    open my $fh, "<", $file;
    print count_words($fh, $search_word) . "\n";
    close $fh;
  }
  else {
    my $stdin = "STDIN";
    my ($search_word) = @ARGV;
    print count_words($stdin, $search_word) . "\n";
  }
}

if ($0 eq __FILE__) {
  main();
}
hoge.txt
hogefugapiyohogefugapiyo
hogehogehogehogehogehoge
$ chmod +x match_count.pl
$ ./match_count.pl hoge.txt hoge
8
$ cat hoge.txt | ./match_count.pl hoge
8
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4