これはありがたい。助かります!
fizzbuzzかいてみた
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#!/usr/bin/perl use strict; my $endNum = 100; my %hashFizzBuzz = ( 'Fizz' => 3 ,'Buzz' => 5 ); for(my $i=1; $i<=$endNum; $i++){ printFizzBuzz($i); } exit 0; sub printFizzBuzz(){ my $num = shift(); my $flag = 0; my @arrayFizzBuzz = keys(%hashFizzBuzz); foreach my $key (@arrayFizzBuzz){ my $result = $num % $hashFizzBuzz{$key}; if($result == 0 ){ print $key if($result == 0 ); $flag = 1; } } print $num if($flag == 0); print "\n"; } |
終了値を引数にして、入力チェックをつけてみた。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#!/usr/bin/perl use strict; my $endNum = validate(\@ARGV); my %hashFizzBuzz = ( 'Fizz' => 3 ,'Buzz' => 5 ); for(my $i=1; $i< =$endNum; $i++){ printFizzBuzz($i); } exit 0; sub printFizzBuzz(){ my $num = shift(); my $flag = 0; my @arrayFizzBuzz = keys(%hashFizzBuzz); foreach my $key (@arrayFizzBuzz){ my $result = $num % $hashFizzBuzz{$key}; if($result == 0 ){ print $key if($result == 0 ); $flag = 1; } } print $num if($flag == 0); print "\n"; } sub validate(){ my $val = shift(); if(@$val != 1){ print "Too many args.\n"; exit 1; } if($val->[0] !~ /^\d+$/ || $val->[0] < = 0 ){ print "input error.\n"; exit 1; } return $val->[0]; } |