開発環境
- 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)の15章(スマートマッチとgiven-when)の15.6(練習問題)4を解いてみる。
その他参考書籍
4.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl use strict; use warnings; use 5.016; use utf8; binmode STDOUT, ':utf8'; binmode STDIN, ':utf8'; given ($ARGV[0]) { when (/\D/) {die "コマンドライン引数には数を指定してください\n";} my @result = divisors($_); my @empty = (); when (@result ~~ @empty) {say "素数";} default {say "約数一覧 @result";} } sub divisors { my $number = shift; my @divisors = (); for ( 2 .. ( $number / 2) ) { push @divisors, $_ unless $number % $_; } return @divisors; }
入出力結果(Terminal)
$ ./sample.pl 99 約数一覧 3 9 11 33 $ ./sample.pl perl Wide character in die at ./sample.pl line 10. コマンドライン引数には数を指定してください $ ./sample.pl 5 素数 $
ちなみにpython3.3の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 ## Copyright (C) 2013 by kamimura #-*- coding: utf-8 -*- import sys, re def divisors(num): divs = [] for n in range(2, num // 2 + 1 ): if num % n == 0: divs.append(n) return divs num = sys.argv[1] if re.search(r"\D", num): print("コマンドライン引数には数を指定してください") else: result = divisors(int(num)) if result == []: print("素数") else: print("約数一覧 {0}".format( " ".join(map(lambda x: str(x), result))))
入出力結果(Terminal)
$ ./sample.py 99 約数一覧 3 9 11 33 $ ./sample.py python コマンドライン引数には数を指定してください $ ./sample.py 5 素数 $
0 コメント:
コメントを投稿