fork download
  1. #!/usr/bin/perl
  2. use 5.016;
  3. use warnings;
  4.  
  5. package _FizzBuzz;
  6. use overload (
  7. '""' => sub{ $_[0]->string || $_[0]->number },
  8. '0+' => sub{ $_[0]->number },
  9. fallback => 1
  10. );
  11.  
  12. sub new { bless [ @_[1, 2] ], (ref $_[0] || $_[0]) }
  13. sub number { $_[0]->[0] }
  14. sub string { $_[0]->[1] }
  15.  
  16. package main;
  17.  
  18. sub _fizz_buzz {
  19. my ($o, $n, $s) = @_;
  20.  
  21. (ref $o eq '_FizzBuzz') ?
  22. $o->new($o->number, $o->string . ($o->number % $n ? '' : $s)) :
  23. _fizz_buzz(_FizzBuzz->new($o, ''), $n, $s)
  24. );
  25. }
  26.  
  27. sub fizz { _fizz_buzz($_[0], 3, 'Fizz') }
  28. sub buzz { _fizz_buzz($_[0], 5, 'Buzz') }
  29. sub gizz { _fizz_buzz($_[0], 7, 'Gizz') }
  30.  
  31. say buzz fizz 1;
  32. say buzz fizz 3;
  33. say buzz fizz 5;
  34. say buzz fizz 15;
  35. say buzz fizz 998;
  36.  
  37. say gizz buzz fizz 7;
  38. say gizz buzz fizz 21;
  39. say gizz buzz fizz 35;
  40. say gizz buzz fizz 105;
  41. say buzz gizz fizz 105;
  42.  
  43. say buzz(fizz(1)) + 2;
  44. say fizz(buzz(fizz(1)) + buzz(2));
  45. say gizz(buzz(fizz(15))) . "XXX";
  46.  
Success #stdin #stdout 0s 3828KB
stdin
Standard input is empty
stdout
1
Fizz
Buzz
FizzBuzz
998
Gizz
FizzGizz
BuzzGizz
FizzBuzzGizz
FizzGizzBuzz
3
Fizz
FizzBuzzXXX