[FB]izzBuzz in Perl

I finally sat down and organized my unsorted bookmarks in Firefox. In doing so I came across Jeff Atwood's blog post describing the FizzBuzz test:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

I must have bookmarked the link while preparing for interviews before graduation. After skimming over the material I was curious to know the smallest amount of Perl code I could use to write a solution.

Here's my attempt:

Any shorter solutions? I suppose I could just use print if I wanted a one-liner...

11 Comments

It's interesting that you are going for the shortest solution. Jeff's post describes a test for hiring programmers. If I were to hire somebody, I'd put all my bets on the candidate delivering the cleanest code and I'd give lots and lots of bonus points if that code was accompanied by unit tests.

You can replace the first two tests with:

!(%_ % 15)

Or (slightly more self-documenting):

!($_ % (3*5))

As someone else has pointed out, brevity is not necessarily what you want to be optimizing for. That said:

say(('Fizz')[$_%3].('Buzz')[$_%5]or$_) for 1..100;

Throws warnings, though.

Slightly longer and uglier, no warnings:

say((('Fizz')[$_%3]||'').(('Buzz')[$_%5]||'')or$_) for 1..100;

I quite like:

say ("Fizz"x!($_%3)."Buzz"x!($_%5)or$_) for 1..100

Are we allowed to use CPAN

  use FizzBuzz;fizzbuzz($_) for 1..100
I'm not even going to check CPAN, I'm sure there will be an implementation there :-)

More p5 & p6 versions at Rosetta Code -

http://rosettacode.org/wiki/FizzBuzz#Perl

Slightly shorter and uglier with no strict subs:

say((Fizz)[$_%3].(Buzz)[$_%5]or$_)for 1..100;

I was trying something different here. Didn't work out as concise as I'd hoped, but it's pretty cute...

say+(Fizz,Buzz,FizzBuzz,$_)[substr+233031033013033,$_%15,1]for 1..100;

Along similar lines; a little shorter...

say+($_,Fizz,Buzz,FizzBuzz)[!($_%3)+2*!($_%5)]for 1..100;

I'm late to the party, but here's my version, using a slightly different approach:

say+(Fizz)[++$_%3].Buzz x/.?[50]$/||$_ until$`

Leave a comment

About curtis

user-pic I blog about Perl.