2012年4月9日月曜日

開発環境

『初めてのPerl 第5版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-427-9) の15章(スマートマッチとgiven-when), 15.6(練習問題)4を解いてみる。

4.

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

コード(TextWrangler)

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

sub divisors{
  my $number = shift;
  my @divisors = ();
  for(2..$number/2){
    push @divisors, $_ unless $number % $_;
  }
  return @divisors;
}

given($ARGV[0]){
  when(/\D+/){say "NaN";}
  my @divisors = divisors $_;
  when(@divisors ~~ []){say "素数";}
  default{say "約数一覧: @divisors";}
}

入出力結果(Terminal)

$ perl sample.pl 99
約数一覧: 3 9 11 33
$ perl sample.pl perl
NaN
$ perl sample.pl 11
素数
$

0 コメント:

コメントを投稿