Guided by a core set of principles and goals, every
language designer is tormented by thousands of
agonizing choices. Gosling chose differently to Wall.
A perhaps unintended side effect of some of Larry's choices
-- such as Perl's "diagonal-ness" and TMTOWTDI --
is that playing golf in Perl is fun.
By contrast, and I've never tried it, I imagine playing golf in Java (or Cobol) would feel oppressive
in the extreme.
Of course, like obfuscation and poetry, only a
minority of Perl programmers actually pursue golf
as a hobby.
James Gosling, for instance, though he readily
acknowledges writing many Perl programs,
has never entered a Perl golf tournament,
to the best of my knowledge.
This, the fourth episode of the long running
series on the lighter side of Perl culture, focuses on
Perl Golf.
History
There were secrets to those IBM machines that had been painstakingly
learned by some of the older people at MIT with access to the 704
and friends among the Priesthood. Amazingly, a few of these programmers,
grad students working with McCarthy, had even written a program that
utilized one of the rows of tiny lights: the lights would be lit in
such an order that it looked like a little ball was being passed from
right to left: if an operator hit a switch at just the right time,
the motion of the lights could be reversed--Computer Ping-Pong!
This obviously was the kind of thing that you'd show off to impress
your peers, who would then take a look at the actual program you
had written and see how it was done.
To top the program, someone else might try to do the same thing with
fewer instructions--a worthy endeavor, since there was so little room
in the small "memory" of the computers of those days that not many
instructions could fit into them. John McCarthy had once noticed how
his graduate students who loitered around the 704 would work over
their computer programs to get the most out of the fewest instructions,
and get the program compressed so that fewer cards would need to be
fed to the machine. Shaving off an instruction or two was almost an
obsession with them. McCarthy compared these students to ski bums.
They got the same kind of primal thrill from "maximizing code" as
fanatic skiers got from swooshing frantically down a hill. So the
practice of taking a computer program and trying to cut off instructions
without affecting the outcome came to be called "program bumming,"
and you would often hear people mumbling things like "Maybe I can
bum a few instructions out and get the octal correction card loader
down to three cards instead of four."
-- John McCarthy's grad students playing golf ("program bumming") in machine language on the IBM 704 computer in 1959 (from Hackers, Heroes of the Computer Revolution by Steven Levy)
I recently read an article where Knuth describes a game of golf on a 50's machine. The machine read cards, and one could put 8 machine instructions on a card. The goal was to write a program fitting on one card that would read in a number, and reverse it.
Noone was able to do it, but Knuth once stunned his fellow students. He came in, put a card in the reader, entered the number 123456789, ran the program, and the program outputted 987654321.
Of course, the program would always output 987654321, regardless of the number on input.
Later, the machine got an extension. A whopping extra register, with front panel toggles. Which could be used to store an instruction as well. Knuth was delighted that that enabled him to write a single card program that reversed a number.
-- Abigail talks about Knuth on comp.lang.perl.misc 23 March 2001
The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague. In the case of a well-known conversational programming language I have been told from various sides that as soon as a programming community is equipped with a terminal for it, a specific phenomenon occurs that even has a well-established name: it is called "the one-liners." It takes one of two different forms: one programmer places a one-line program on the desk of another and either he proudly tells what it does and adds the question, "Can you code this in less symbols?"---as if this were of any conceptual relevance!---or he just says, "Guess what it does!". From this observation we must conclude that this language as a tool is an open invitation for clever tricks; and while exactly this may be the explanation for some of its appeal, viz., to those who like to show how clever they are, I am sorry, but I must regard this as one of the most damning things that can be said about a programming language.
-- Edsger Wybe Dijkstra (1930-2002) in his 1972 essay: The Humble Programmer (cited in On Golf)
As indicated by the quotes above, playing golf in
computer languages started long before Perl did.
It's just that it wasn't called golf back then.
Perl's main claim to fame in this golf business is that
a Perl hacker, namely Greg Bacon, actually coined the term
Perl Golf
in a comp.lang.perl.misc thread on 28 May 1999.
And the term golf has been applied to other
computer languages since then.
Ironically, Greg may have intended the term as
derogatory -- just as
Fred Hoyle
coined the term "Big Bang" to mock that theory --
because Greg
once dismissed golf as really, really boring.
As you might expect, the earliest exponents of Perl Golf
were probably Larry and Randal. For example,
here
is an early golfish Larry post from March 1990. And in
this one
Larry implies that Randal was his golfing buddy in those
early days.
In March 1995, Adam Back and Hal Finney caused a stir by implementing RSA encryption and decryption in Perl as a signature file. Later Clifford Adams and others joined in the fun.
In September 1995, in what was probably the first golf contest with money prizes, the surprising winner of this
comp.programming.contests C golf contest
was a Perl hacker (some might say the
Perl hacker;-).
The goal of this competition was to find the shortest
C program that reverses all words in a file.
I found this exchange amusing.
: >Well, if that's your goal, you're gonna have to work a little harde
+r.
: >I sent this out last week, but it never made it off my machine. It
+'s
: >50 characters, counting the final newline.
: >
: > main(){system("perl -pe 's/\\w+/reverse$&/eg'");}
: >
: >It's almost readable, too.
: >
: >Larry Wall
:
: Well, if we're allowed to write our own interpreters then yours is
: easy to beat!
:
: main(){system("a");}
:
: 20 characters! (Not counting the final newline.)
:
: You haven't heard of my interpreter "a"? Well it just so happens
: that, without any command line arguments, it filters stdin to stdout
: in a manner that is identical to any of the valid entries to this
: competition, like your entry above for example. :-)
:
: John Ellson
Well, hey, I said you'd have to work a *little* harder, not a lot hard
+er. :-)
Larry
Jumping forward to July 2000, Uri Guttman initiated the
ill-fated
Perl Golf Apocalypse
scheduled to run, accompanied by witty commentary,
in front of a live audience at TPC 4.
Alas, a number of technical glitches caused the event
to be cancelled, replaced by a Damian Conway talk.
Given that Larry was in the audience, it's little
wonder that Uri is still
scarred
by it today. To my knowledge, no one has been brave enough
to attempt a live Perl Golf contest since.
The Apocalypse questions formed part of a golf
competition run by jmcnamara in PGA Golf, Round 1 and
PGA Golf, Round 1 - Results here at the monastery. I note with
interest that mtve found some improvements to the
original contest solutions some years later
(this seems to be a speciality of mtve and
thospel).
During 2001, there was such a rush of golf posts
here at the monastery, that chipmunk
sent out a plea, Tips on Writing a Golf Challenge, to calm things
down a bit.
Just before Christmas 2001, the fwp mailing list
exploded with a flurry of golf threads, starting with the
Santa Claus Golf Apocalypse
won by Eugene van der Pijll. This tournament introduced
an innovation: strict rules and a test program that all
entries must pass before being accepted. A much improved
version of this early test program can be found
here.
These golf contests spawned a new mailing list
golf@perl.org, split off from fwp.
A new magazine,
The Perl Review,
launched early in 2002, sponsored a series
of golf tournaments run at SourceForge
by Dave Hoover and Jérôme Quelin. These tournaments
were run monthly throughout 2002, the top five money
winners at the end of season being:
1 Ton Hospel $ 4,384,000.00 (10/13)
2 Rick Klement $ 3,712,000.00 (12/13)
3 Eugene van der Pijll $ 3,540,000.00 (10/13)
4 Stephen Turner $ 1,955,200.00 (11/13)
5 Mtv Europe $ 1,837,040.00 (9/13)
In 2003, the TPR tournaments moved to
Terje Kristensen's minigolf site
where Ton Hospel, Mtv Europe and Rick "tybalt89" Klement continued to dominate. Around this time, golf enjoyed a surge of popularity in Poland, courtesy of games run at the kernelpanic.pl web site and the Polish comp.lang.perl newsgroup.
After two to three seasons, these sites became inactive and the game of Perl Golf transmogrified into Code Golf. Serious golf competitions in Perl, Python, Ruby and PHP are nowadays run at Code Golf, while less serious ones (in 51 different languages) are played at shinh's golf site.
What is Perl Golf?
Is it an art, a sport, just a bit of fun,
a waste of time, or a threat to sound coding
practices?
I don't want to dwell too much on this; it is
different things to different people.
Hopefully, as with obfuscation, people are sensible
enough to not start golfing on production code.
My personal view is that golf is mostly about fun
and competition.
As for the usefulness of Perl golf, apart from being
a fun way to explore TMTOWTDI, notice that
Perl golf, by its nature, pushes the language to
its limits, often exercising boundary conditions.
It should come as no surprise therefore that quite a
few perl bugs have been unearthed during golf
tournaments, especially by Ton Hospel.
Golf Competitions
I think Felix (the contest judge) made a bad judgement,
because the winning program was not nearly as confusing
as mine---it was actually very simple.
-- MJD on TPJ OPC 5 judging at
perl.plover.com
Competitions requiring judges, such as Olympic gymnastics
and obfuscated Perl competitions, are easily spoiled
by poor judging, as alluded to above by MJD.
The wonderful thing about Perl Golf
competitions compared to obfuscated ones is that golf
is typically judged simply by counting up the number
of characters in your solution. I've never seen any
ugly disputes or complaints about who should have won.
Of course, the winning golf solution may be horribly
ugly or highly inefficient. So several people have
suggested alternative types of competitions,
judged by different criteria. Perhaps the most commonly
suggested is the 100 metre dash where each solution
is timed and the fastest wins. A novel twist on this idea
is to measure not the CPU or wall clock time, but the
number of Perl ops. For more information on Perl ops see
Nicholas Clark's excellent paper "when perl is not quite fast enough". Yet another alternative is
MJD's Perl Quiz of the Week
where human judges comment on the "quality" of
a solution after a 60 hour grace period.
The story goes that Marshall discovered this variation
9 years before he played it, and avoided defending with
the Ruy Lopez for 9 years until he had a chance to
spring it on Capablanca.
-- Quote taken from
note by Bill Wall (any relation to Larry?)
It's a mark of Capablanca's genius that he was able
to refute over the board a variation his grandmaster
opponent had been studying and preparing for nine years.
In similar style to Capablanca, during the TPR tournaments
four expert golfers would sometimes cook up a problem,
study it in consultation for a month, and conclude
the best solution possible was, say, 120 strokes.
Yet within a couple of hours, the remarkable Ton
Hospel would then go and post a score of around 100!
In many ways, Perl Golf tournaments resemble
a fiercely contested chess tournament.
Some Classic Golf Games
One golf that seems to come up again and again is the
famous 99 bottles of beer song. It's been
discussed here at the monastery in: 99 bottles, 2 lines, 99 Bottles Of Beer (can't we do better), 99 bottles of beer on the Wall, Golf: Back to those damn beer bottles again... and Bottle Golf. For the record, I believe the shortest
known solution is not in any of those nodes, but was
concocted by thospel and mtve as follows:
sub
b{[@b=(abs||No,bottle."s"x!!++$_,of,beer),on,the,wall]}print
"@{+b},\n@b,\nTake one down, pass it around,\n@{+b}.\n"
for-pop||-99..-1
This version takes a command line argument specifying
the number of bottles (default 99). If you find a
shorter one, respond away!
May 2011 Update: Shorter bottle golf solutions are now described in
Drunk on golf: 99 Bottles of Beer.
The most interesting golf games occur when several
solutions, all with a similar score, are possible.
To illustrate, consider
TPR(0,5a),
an infix to postfix converter. This problem could be
solved with: an operator stack; via overload; a recursive
regex; top-down parsing; or
Eugene's winning Mad Dutch algorithm
(invented for this game). Sometimes, a truly
astonishing approach is found, as when
Jukka Suomela in
TPR(0,4b)
observed that perl itself has a built-in topological sorter: the garbage collector. Chris Dolan's
explanation can be found
here.
Some Standard Golfing Techniques
Common operations should be "Huffman coded." That is, frequently used operators should be shorter than infrequently used ones.
-- Larry Wall in Apocalypse 3
: OK. Still, it'd be nice to get anonymous scalars somehow.
The Huffman encoding of that is do{\my$x}.
-- Larry Wall on p5p, 30 April 1999
An excellent introduction to the basics of shortening your Perl code be found in Perl Golf 101.
As discussed in
this thread (update: and this thread and here), some well-known golfing techniques are:
Golfing Technique Inventor Year
----------------- -------- ----
@{[]} aka baby cart The Larry or 1994
The Schwartz
}{ aka eskimo greeting The Abigail late 1990s
~~ aka inchworm ???
~- aka inchworm-on-a-stick The Hospel 2002
$_ x= boolean expression The Larry early 1990s
y///c aka Abigail's Length Horror The Hall 1996
stuff value into $\ for printing The van der Pijll 2001
}for(...){ variation of eskimo The Hospel 2001
--$| magical flip-flop The Hospel 2002
\$h{X} is one less than ++$h{X}
aka Thelen's Device The Thelen 2002
-i and $^I for data value The Sperling 2002
References
- What: golf and benchmarks, Where: snippets, When: from now on, Why: for fun and glory!
- Golf Do-s and Don't-s
- Another golf style?
- On Golf
- Masem home node with many PM golf links
- Tips on Writing a Golf Challenge
- PGA Golf, Round 1
- PGA Golf, Round 1 - Results
- Book Idea: The Golfer's Handbook
- Fun With Perl: Golf
- Golfing and Sprinting
- MoleSter update - Golf
- Perl Golf 101
- USD $350 Cash First Prize for Perl Golf Competition
- Perl Golf Ethics
- Dueling Flamingos: The Story of the Fonality Christmas Golf Challenge
- The golf course looks great, my swing feels good, I like my chances (Part I)
- The golf course looks great, my swing feels good, I like my chances (Part II)
- The golf course looks great, my swing feels good, I like my chances (Part III)
- The golf course looks great, my swing feels good, I like my chances (Part IV)
- The golf course looks great, my swing feels good, I like my chances (Part V)
- The golf course looks great, my swing feels good, I like my chances (Part VI)
- Drunk on golf: 99 Bottles of Beer
- Compression in Golf: Part I
- Larry plays golf with himself (and Randal)
- Larry golfing again
- Original Perl RSA program posted to cypherpunks list 9 Mar 1995 by Adam Back, response by Hal Finney
- RSA signature file in Perl history
- Larry wins money prize in comp.programming.contests C golf contest, Sep 11 1995
-
Greg Bacon coins the term Perl Golf
- ircnet #perl golf challenge, Christmas 2001
- Ton Hospel's generic golf tester
- TPR Golf Contests
- terje's mini golf site
-
Terje/mtv pdf book about Perl Golf
- Polish Perl Golf site
- perl golf mailing list archive
- Final TPR Career Money Leader List
-
Perl Golf Apocalypse Invite
-
First ever Perl 6 golf post cited in this 2002 Perl 6 Summary
- c2.com PerlGolf entry
- Shortest Wiki Contest
- Shortest Sudoku Solver in many different languages by Mark Byers
- Golf competitions in Perl, Ruby, Python or PHP
- PHP golf site
- Golf competitions in Vim
- Golf games played in 51 different languages (under construction by shinh)
- stackexchange codegolf and programming puzzles question and answer
- codegolf books (see especially hallvabo answer which mentions Japanese "Short Coding" book by Ozy)
- Sphere online judge (SPOJ) programming competitions
- Golf competitions in C (beta)
-
MJD's Perl Quiz of the Week
-
Larry Wall Articles and Interviews
- Damian Conway interviewed by Builder AU
- Interview with Dennis Ritchie, Bjarne Stroustrup, and James Gosling
- Some quotes about programming languages
- history.perl.org Perl Timeline
- Python golf contest
- Nicholas Clark YAPC::Eu paper: when perl is not quite fast enough
- Edsger Dijkstra manuscript archive
- Hackers, Heroes of the Computer Revolution by Steven Levy
- Code golf (wikipedia)
Other Articles in This Series
Updated aug 2011: Added John McCarthy (1959) and RSA (1995) reference.