I mean, other than “The Adventures of Accordian Guy in the Twenty-First Century“?
Yes, yes he does.
I ran across this on the Y Combinator Twitter yesterday, and thought I’d give FizzBuzz a shot. I’d estimate it took me just under 30 minutes to get the code you see here, which I believe “works”. Part of that time was taken up with assisting one of my cow orkers with a problem, though. An embarrassingly large chunk of that time was taken up by my having to look up the Perl syntax for “for”, “if”, and the modulo operator. I’m a bit rusty; the last time I wrote substantial Perl code was about a year ago (a Perl script that parses CSV data from a file and imports it into a SQL database).
Anyway, code:
#!/usr/bin/perl
for ($index = 1; $index < 101; $index++)
{
$div_by_3 = 0;
$div_by_5 = 0;
if ($index % 3 == 0) {
$div_by_3 = 1;
}
if ($index % 5 == 0) {
$div_by_5 = 1;
}
if ($div_by_3 == 1 && $div_by_5 == 1 ) {
printf "FizzBuzz\n";
} else {
if ($div_by_3 == 1) {
printf "Fizz\n";
} else {
if ($div_by_5 ==1){
printf "Buzz\n";
} else {
printf "$index\n";
}
}
}
}
As always, when I put stuff like this up, I welcome criticism or comment on how I could have done it better (or, in this case, “right” if I did it wrong). The way I see it, I can’t get any better if I don’t solicit and accept criticism.
(Followup from deVilla here.)
Edited to add: I was going to upload a Python version that I wrote in (about) 20 minutes (I think). I keep planning to sit down and learn Python, but then somebody calls and wants to go riding bikes or whatever…anyway, I couldn’t paste that here and have it come out the way I wanted to, so I’ve uploaded it here. (I had to change the extension from “.py” to “.txt” because WordPress didn’t like “.py”.)
Your code looks a lot like C, which isn’t necessarily a bad thing. 🙂
Here’s my perl implementation.
foreach (1..100)
{ (0 == ($_ % 3)) && (0 == ($_ % 5)) && (print “FizzBuzz\n”) && next;
(0 == ($_ % 3)) && (print “Fizz\n”) && next;
(0 == ($_ % 5)) && (print “Buzz\n”) && next;
print “$_\n”;
}
Bruce:
That’s a very kind thing for you to say. Thank you.
I think you’re better at what I call “idiomatic Perl” than I am. I understand (or at least can look up) constructs like “$_”, but I don’t think in those concepts the way some people seem to.
So my Perl is probably much more verbose than it needs to be…
Much depends on what you’re trying to optimize for. Reader effort is a valuable resource, even your own, and your example requires less of it than mine. I also notice that you took the trouble to avoid repeating the modulo tests, while mine will do both tests twice in most cases.