開発環境
- OS X Mavericks - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs (Text Editor)
- Perl (プログラミング言語)
初めてのPerl 第6版 (Randal L. Schwartz (著)、brian d foy (著)、Tom Phoenix (著)、近藤 嘉雪 (翻訳)、オライリージャパン)、15章(スマートマッチとgiven-when)の15.6(練習問題)5.を解いてみる。
その他参考書籍
15.6(練習問題)5.
コード(BBEdit, Emacs)
sample5.pl
#!/usr/bin/env perl
# use diagnostics;
use strict;
use warnings;
use 5.016;
use utf8;
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';
sub divisors {
my $number = shift;
my @divisors = ();
for (2 .. ( $number / 2)) {
push @divisors, $_ unless $number % $_;
}
@divisors;
}
my $fav = 10;
given ($ARGV[0]) {
when (/\D+/) { say "Not a number."; }
my @divisors = divisors $_;
my @temp;
when (! (2 ~~ @divisors)) { say "その数は奇数である。"; continue;}
when (2 ~~ @divisors) { say "その数は偶数である"; continue;}
when ($fav ~~ @divisors || $fav == $_) {
say "その数は好きな数($fav)の倍数である。"; continue;}
when (@divisors ~~ @temp) { say "その数が素数である。"; continue;}
default {say "約数一覧: @divisors";}
}
入出力結果(Terminal)
$ ./sample5.pl 2 その数は奇数である。 その数が素数である。 約数一覧: $ ./sample5.pl 3 その数は奇数である。 その数が素数である。 約数一覧: $ ./sample5.pl 4 その数は偶数である 約数一覧: 2 $ ./sample5.pl 5 その数は奇数である。 その数が素数である。 約数一覧: $ ./sample5.pl 6 その数は偶数である 約数一覧: 2 3 $ ./sample5.pl 7 その数は奇数である。 その数が素数である。 約数一覧: $ ./sample5.pl 8 その数は偶数である 約数一覧: 2 4 $ ./sample5.pl 9 その数は奇数である。 約数一覧: 3 $ ./sample5.pl 10 その数は偶数である その数は好きな数(10)の倍数である。 約数一覧: 2 5 $ ./sample5.pl 100 その数は偶数である その数は好きな数(10)の倍数である。 約数一覧: 2 4 5 10 20 25 50 $ ./sample5.pl 99 その数は奇数である。 約数一覧: 3 9 11 33 $
0 コメント:
コメントを投稿