開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Perl
『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2)の17章(上級テクニック)の17.6(練習問題)1を解いてみる。
その他参考書籍
1.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl use strict; use warnings; use 5.016; use utf8; binmode STDOUT, ':utf8'; binmode STDIN, ':utf8'; binmode STDERR, ':utf8'; my $filename = 'sample.txt'; open my $fh, '<', $filename or die "can't open $filename: $!"; chomp(my @strings = <$fh>); while (1) { print "パッターンを入力: "; chomp(my $pattern = <STDIN>); last if $pattern =~ /^\s*$/; my @matched = eval { grep /$pattern/, @strings }; if ($@) { say $@; } else { say @matched + 0, '個'; say join "\n", @matched; } }
入出力結果(Terminal)
$ cat sample.txt fred barney fred dino wilma fred $ ./sample.pl パッターンを入力: ( Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE / at ./sample.pl line 20, <STDIN> line 1. パッターンを入力: d 4個 fred fred dino fred パッターンを入力: ^d 1個 dino パッターンを入力: d$ 3個 fred fred fred パッターンを入力: $
ちなみにpython3.3の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 ## Copyright (C) 2013 by kamimura #-*- coding: utf-8 -*- import re filename = 'sample.txt' with open(filename) as f: strs = f.readlines() while True: pattern = input("パターンを入力: ") if re.search(r"^\s*$", pattern): break try: matched = [s for s in strs if re.search(r"{0}".format(pattern), s)] print("".join(matched), end="") except Exception as err: print(type(err), err, err.args)
入出力結果(Terminal)
$ cat sample.txt fred barney fred dino wilma fred $ ./sample.py パターンを入力: ( <class 'sre_constants.error'> unbalanced parenthesis ('unbalanced parenthesis',) パターンを入力: d fred fred dino fred パターンを入力: ^d dino パターンを入力: d$ fred fred fred パターンを入力: $
0 コメント:
コメントを投稿