2020年6月12日金曜日

開発環境

初めてのPerl 第7版 (Randal L. Schwartz(著)brian d foy(著)Tom Phoenix(著)近藤 嘉雪(翻訳)嶋田 健志(翻訳)、オライリージャパン)の16章(上級テクニック)、16.6(練習問題)1の解答を求めてみる。

コード

#!/usr/bin/env perl
use strict;
use warnings;
use v5.28;

say '1.';

my $filename = 'sample_text.txt';

open my $in_fh, '<', $filename or die "Can't open file $filename: $!";

chomp(my @strs = <$in_fh>);

while (1) {
    print 'パターンを入力(空行で終了): ';
    chomp(my $pattern = <STDIN>);
    last if $pattern =~ /\A\s*\Z/;
    my @matched = eval {grep /$pattern/, @strs };
    if ($@) {
        say $@;
        redo;
    }
    print "マッチした個数: ", @matched + 0, "\n";
    print "マッチした文字列\n";
    foreach (@matched) {
        say;
    }
}

入出力結果(Zsh、PowerShell、Terminal)

% ./sample1.pl 
1.
パターンを入力(空行で終了): ab
マッチした個数: 5
マッチした文字列
betty agreed. "barney and fred never think about us. we should
strikers. how about if i take you out on monday night?"
"that's it, then," said betty. i'll create a distraction at about
mister fred flintstone. is mister fred flintstone available to
"yes, yes," said fred. wilma stood by, curious about this
パターンを入力(空行で終了): [a
Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE a/ at ./sample1.pl line 18, <STDIN> line 2.

パターンを入力(空行で終了): [0-9]
マッチした個数: 3
マッチした文字列
use this with Chapter 17, Exercise 1
past 8."
8. the alley is just around the corner from the restaurant, so
パターンを入力(空行で終了): \Aa
マッチした個数: 3
マッチした文字列
as he headed again toward the door, wilma emerged from the
at that moment, fred rushed back into the house, having left the
after you're gone, betty and i will get your bowling ball and
パターンを入力(空行で終了):  
% 

0 コメント:

コメントを投稿