fizzbuzzかいてみた


#!/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";
}

終了値を引数にして、入力チェックをつけてみた。

#!/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];
}