2012年7月9日月曜日

開発環境

『初めてのPerl 第5版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-427-9) の17章(上級テクニック), 17.6(練習問題)1を解いてみる。

1.

コード(TextWrangler)

#!/usr/bin/env perl
use strict;
use warnings;

my $file = $ARGV[0];
open FILE,$file or die "can't open $file:$!";
chomp(my @strings = <FILE>);
while(1){
  print "パターンを入力: ";
  chomp(my $pattern = <STDIN>);
  last if $pattern =~ /^\s*$/;
  my @matched = eval{
    grep /$pattern/, @strings;
  };
  if($@){
    print "$@";
  } else {
    print "マッチしたものの個数: ",@matched + 0,"\n";
    print "マッチした文字列一覧\n";
    for(@matched){
      print "$_\n";
    }
  }
}

入出力結果(Terminal)

$ ./sample.pl sample_text
パターンを入力: (
Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE / at ./sample.pl line 13, <STDIN> line 1.
パターンを入力: [
Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE / at ./sample.pl line 13, <STDIN> line 2.
パターンを入力: \(
マッチしたものの個数: 1
マッチした文字列一覧
for repeated words, for example. (don't actually try to read this
パターンを入力: \[
マッチしたものの個数: 0
マッチした文字列一覧
パターンを入力: ^a
マッチしたものの個数: 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 コメント:

コメントを投稿