2013年1月21日月曜日

開発環境

『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也田中 慎司吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9)の2章(中級者の基礎知識), 2.4(練習問題)1を解いてみる。

その他参考書籍

1.

コード(BBEdit)

sample.pl

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

my $dir = "/etc/";

chdir "/etc" or die "$!";

while(1){
  chomp(my $pattern = <STDIN>);
  last if $pattern =~ /^\s*$/;
  my @matched = map {"$_\n"} grep{ eval{ /$pattern/ } } glob ".* *";
  if($@){
    warn $@;
  } else {
    print @matched;
  }
}

入出力結果(Terminal)

$ ./sample.pl
lo
csh.login
csh.logout
kern_loader.conf
localtime
locate.rc
mach_init_per_login_session.d
newsyslog.conf
newsyslog.d
syslog.conf
^lo
localtime
locate.rc
[
Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE / at ./sample.pl line 16, <STDIN> line 3.
]
(
Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE / at ./sample.pl line 16, <STDIN> line 5.
)
Unmatched ) in regex; marked by <-- HERE in m/) <-- HERE / at ./sample.pl line 16, <STDIN> line 6.
\(

$

pythonの場合。

sample.py

コード(BBEdit)

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

import os, re, glob

os.chdir("/etc/")
files = glob.glob("*")
while True:
 pattern = input()
 if re.search(r"^\s*$", pattern): break
 matched = []
 try:
     for s in files:
         if re.search(pattern, s):
          matched.append(s)
 except Exception as err:
         print(err)
 else:
     print(matched)

入出力結果(Terminal)

$ ./sample.py
lo
['csh.login', 'csh.logout', 'kern_loader.conf', 'localtime', 'locate.rc', 'mach_init_per_login_session.d', 'newsyslog.conf', 'newsyslog.d', 'syslog.conf']
^lo
['localtime', 'locate.rc']
[
unexpected end of regular expression
]
[]
(
unbalanced parenthesis
)
unbalanced parenthesis
\(
[]

$

0 コメント:

コメントを投稿