2012年3月11日日曜日

開発環境

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

1.

やり方の1つ。(「やり方は何通りもある」(TIMTOWTDI(There Is More Than One Way To Do It.)))

コード(TextWrangler)

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

while(<>){
  chomp;
  if(/match/){
    print "Matched: |$`<$&>$'|\n";
  } else {
    print "No match: |$_|\n";
  }
}

入出力結果(Terminal)

$ ./perl_program
beforematchafter
Matched: |before<match>after|
$

2.

用意したファイル、test

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

やり方の1つ。(「やり方は何通りもある」(TIMTOWTDI(There Is More Than One Way To Do It.)))

コード(TextWrangler)

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

while(<>){
  chomp;
  if(/a\b/){
    print "Matched: |$`<$&>$'|\n";
  } else {
    print "No match: |$_|\n";
  }
}

入出力結果(Terminal)

$ ./perl_program test
No match: |A|
Matched: |<a>|
Matched: |kamimur<a>'s blog|
Matched: |http://sitekamimur<a>.blogspot.com|
No match: |KMI|
Matched: |http://www.mkamimur<a>.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: |wilam<a>|
No match: |barney|
Matched: |wilm<a> and fred|
Matched: |fred and wilm<a>|
Matched: |Wilm<a> and Fred      |
Matched: |Fred and Wilm<a>|
Matched: |wilm<a>&fred|
Matched: |Mrs. Wilm<a> Flintstone   |
Matched: |I saw Wilm<a> yesterday|
Matched: |I, Wilm<a>!|
No match: |Z|
Matched: |llam<a>|
$

0 コメント:

コメントを投稿