2012年9月7日金曜日

開発環境

『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2) の8章(正規表現によるマッチ)、8.10(練習問題)5を解いてみる。

5.

コード(TextWrangler)

sample.pl

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.012;
binmode STDOUT, ':utf8';
binmode STDIN, ':utf8';

my $what = 'word';
while(<>){
  chomp;
  if(/\b(?<$what>\w*a)\b(?<after>.{0,5})/){
    print "Matched: |$`<$&>$'|\n";
    print "'$what' contains '$+{$what}'\n";
    print "続く最大5文字: '$+{after}'\n";
  } else {
    print "No match: |$_|\n";
  }
}

入出力結果(Terminal)

$ ./sample.pl test.txt
No match: |A|
Matched: |<a>|
'word' contains 'a'
続く最大5文字: ''
Matched: |<kamimura's bl>og|
'word' contains 'kamimura'
続く最大5文字: ''s bl'
Matched: |http://<sitekamimura.blog>spot.com|
'word' contains 'sitekamimura'
続く最大5文字: '.blog'
No match: |KMI|
Matched: |http://www.<mkamimura.com >  |
'word' contains 'mkamimura'
続く最大5文字: '.com '
No match: |Fred|
No match: |FRED|
No match: |fred|
No match: |frederick|
No match: |Alfred|
No match: |fred flintstone|
No match: |Mr. Slate     |
No match: |Mississippi|
No match: |Bamm-Bamm    |
Matched: |<wilama>|
'word' contains 'wilama'
続く最大5文字: ''
No match: |barney|
Matched: |<wilma and >fred|
'word' contains 'wilma'
続く最大5文字: ' and '
Matched: |fred and <wilma>|
'word' contains 'wilma'
続く最大5文字: ''
Matched: |<Wilma and >Fred      |
'word' contains 'Wilma'
続く最大5文字: ' and '
Matched: |Fred and <Wilma>|
'word' contains 'Wilma'
続く最大5文字: ''
Matched: |<wilma&fred>|
'word' contains 'wilma'
続く最大5文字: '&fred'
Matched: |Mrs. <Wilma Flin>tstone   |
'word' contains 'Wilma'
続く最大5文字: ' Flin'
Matched: |I saw <Wilma yest>erday|
'word' contains 'Wilma'
続く最大5文字: ' yest'
Matched: |I, <Wilma!>|
'word' contains 'Wilma'
続く最大5文字: '!'
No match: |Z|
Matched: |<llama>|
'word' contains 'llama'
続く最大5文字: ''
$ cat test.txt
A
a
kamimura's blog
http://sitekamimura.blogspot.com
KMI
http://www.mkamimura.com   
Fred
FRED
fred
frederick
Alfred
fred flintstone
Mr. Slate     
Mississippi
Bamm-Bamm    
wilama
barney
wilma and fred
fred and wilma
Wilma and Fred      
Fred and Wilma
wilma&fred
Mrs. Wilma Flintstone   
I saw Wilma yesterday
I, Wilma!
Z
llama
$

0 コメント:

コメントを投稿