8 Queens in Perl and Ruby


[go to the Programming Republic of Perl]

A long time ago while I was living in Boston I got to know Jon Orwant. When he started publishing a magazine devoted to Perl and things related it was suggested that I might want to write an article for it. The magazine was The Perl Journal, and I finally got around to writing an article in time for Issue 4.

8 Queens:

The 8 queens problem is quite simple. Given an 8×8 chess board, how can 8 queens be arranged on the board so that none is threatening any of the others.

Timothy Budd used the 8 queens problem as an example in the first edition of his book An Introduction to Object-Oriented Programming (see his list of books). I simply translated the Objective C version into perl and described the problem in the article.

The Code:

The code consists of 3 files:


This is the driver which sets up the initial board and then asks the queens to sort themselves out.


This file defines the Queen module which contains the Queen class.


This file defines the Queen::Null module which contains the Queen::Null class.

The Ruby Code:

The same solution has been implemented in Ruby in a single file 8q.rb. This is just an experiment in playing with Ruby, and may not be idiomatic. It does seem cleaner than Perl, even if there isn’t a use strict; to keep me on the straight and narrow.