13

I've seen many (code-golf) Perl programs out there and even if I can't read them (Don't know Perl) I wonder how you can manage to get such a small bit of code to do what would take 20 lines in some other programming language.

  • What is the secret of Perl? Is there a special syntax that allows you to do complex tasks in few keystrokes? Is it the mix of regular expressions?

I'd like to learn how to write powerful and yet short programs like the ones you know from the code-golf challenges here. What would be the best place to start out? I don't want to learn "clean" Perl - I want to write scripts even I don't understand anymore after a week.

If there are other programming languages out there with which I can write even shorter code, please tell me.

Cœur
  • 37,241
  • 25
  • 195
  • 267
sak
  • 147
  • 3
  • 3
    Although one might wonder about the goal -- "I want to write scripts even I don't understand anymore after a week" -- this is a perfectly reasonable and answerable question. It should be reopened. A good answer would note things like (a) Perl's history coming out of a sys admin, sed, awk culture; (b) Perl's use of special variables and run options to facilitate the development of one-liner scripts within the context of Unix pipelines; (c) Perl's default argument `$_`; and probably some other stuff. – FMc Apr 11 '10 at 13:27
  • 2
    This was closed with the reason "It's impossible to objectively answer this question; questions of this type are too open ended and usually lead to confrontation and argument." The part about "confrontation and argument" is completely and utterly bogus - this question will not lead to confrontation and argument. I've voted to reopen. If you want to close something, close it for a real reason, please. –  Apr 11 '10 at 14:03
  • @Kinopiko: ok, well, cwiki? It clearly doesn't have one right answer. – bmargulies Apr 11 '10 at 23:25
  • I think this should be community wiki – John La Rooy Apr 12 '10 at 00:45
  • 7
    I disagree. "What are the characteristics of Perl which make it so good for golfing?" clearly *does* have objectively correct (i.e., "right") answers. – Dave Sherohman Apr 12 '10 at 10:58
  • Just curious: why do you want to write programs that you won't understand a week later? I just hope you understand that all the things people do to get their code golf answers so small are *really bad practices*! – Igby Largeman Apr 12 '10 at 20:52

7 Answers7

32

There are a number of factors that make Perl good for code golfing:

  • No data typing. Values can be used interchangeably as strings and numbers.
  • "Diagonal" syntax. Usually referred to as TMTOWTDI (There's more than one way to do it.)
  • Default variables. Most functions act on $_ if no argument is specified. (A few act on @_.)
  • Functions that take multiple arguments (like split) often have defaults that let you omit some arguments or even all of them.
  • The "magic" readline operator, <>.
  • Higher order functions like map and grep
  • Regular expressions are integrated into the syntax (i.e. not a separate library)
  • Short-circuiting operators return the last value tested.
  • Short-circuiting operators can be used for flow control.

Additionally, without strictures (which are off be default):

  • You don't need to declare variables.
  • Barewords auto-quote to strings.
  • undef becomes either 0 or '' depending on context.

Now that that's out of the way, let me be very clear on one point:

Golf is a game.

It's great to aspire to the level of perl-fu that allows you to be good at it, but in the name of $DIETY do not golf real code. For one, it's a horrible waste of time. You could spend an hour trying to trim out a few characters. Golfed code is fragile: it almost always makes major assumptions and blithely ignores error checking. Real code can't afford to be so careless. Finally, your goal as a programmer should be to write clear, robust, and maintainable code. There's a saying in programming: Always write your code as if the person who will maintain it is a violent sociopath who knows where you live.

So, by all means, start golfing; but realize that it's just playing around and treat it as such.

Michael Carman
  • 30,628
  • 10
  • 74
  • 122
  • Excellent answer. I also have this feeling that Perl's orientation toward lists might be useful for golfing, but I'm not certain and I'm not sure how to phrase it. – FMc Apr 11 '10 at 21:32
  • 3
    Perl has data typing. It just doesn't require the programmer to tell Perl what the types are -- it's assumed that the programmer will keep them straight. – jrockway Apr 12 '10 at 08:50
  • 1
    Jon almost has it right. Perl is very strongly typed. A scalar is a scalar, and array is an array, and a hash is a hash. You can't change a variable's type. It just doesn't try to further divide what you put in a scalar. It's just a single value. However, Perl does track string, integer, and floating point versions for scalar values behind the scenes. – brian d foy Apr 12 '10 at 11:08
10

Most people miss the point of much of Perl's syntax and default operators. Perl is largely a "DWIM" (do what I mean) language. One of it's major design goals is to "make the common things easy and the hard things possible".

As part of that, Perl designers talk about Huffman coding of the syntax and think about what people need to do instead of just giving them low-level primitives. The things that you do often should take the least amount of typing, and functions should act like the most common behavior. This saves quite a bit of work.

For instance, the split has many defaults because there are some use cases where leaving things off uses the common case. With no arguments, split breaks up $_ on whitespace because that's a very common use.

 my @bits = split;

A bit less common but still frequent case is to break up $_ on something else, so there's a slightly longer version of that:

 my @bits = split /:/;

And, if you wanted to be explicit about the data source, you can specify the variable too:

 my @bits = split /:/, $line;

Think of this as you would normally deal with life. If you have a common task that you perform frequently, like talking to your bartender, you have a shorthand for it the covers the usual case:

The usual

If you need to do something, slightly different, you expand that a little:

The usual, but with onions

But you can always note the specifics

A dirty Bombay Sapphire martini shaken not stirred

Think about this the next time you go through a website. How many clicks does it take for you to do the common operations? Why are some websites easy to use and others not? Most of the time, the good websites require you to do the least amount of work to do the common things. Unlike my bank which requires no fewer than 13 clicks to make a credit card bill payment. It should be really easy to give them money. :)

brian d foy
  • 129,424
  • 31
  • 207
  • 592
8

This doesn't answer the whole question, but in regards to writing code you won't be able to read in a couple days, here's a few languages that will encourage you to write short, virtually unreadable code:

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • +1 more for J. See for example the last program I wrote in J (with explanation): http://stackoverflow.com/questions/2639281/code-golf-the-mandelbrot-set/2643044#2643044 – David Apr 15 '10 at 20:30
7

Perl has a lot of single character special variables that provide a lot of shortcuts eg $. $_ $@ $/ $1 etc. I think it's that combined with the built in regular expressions, allows you to write some very concise but unreadable code.

Tom Jefferys
  • 13,090
  • 2
  • 35
  • 36
4

Perl's special variables ($_, $., $/, etc.) can often be used to make code shorter (and more obfuscated).

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
1

I'd guess that the "secret" is in providing native operations for often repeated tasks.

In the domain that perl was originally envisioned for you often have to

  • Take input linewise
  • Strip off whitespace
  • Rip lines into words
  • Associate pairs of data
  • ...

and perl simple provided operators to do these things. The short variable names and use of defaults for many things is just gravy.

Nor was perl the first language to go this way. Many of the features of perl were stolen more-or-less intact (or often slightly improved) from sed and awk and various shells. Good for Larry.

Certainly perl wasn't the last to go this way, you'll find similar features in python and php and ruby and ... People liked the results and weren't about to give them up just to get more regular syntax.

dmckee --- ex-moderator kitten
  • 98,632
  • 24
  • 142
  • 234
-2

What's Java's secret of copying a variable in only one line, without worrying about buses and memory? Answer: the code is transformed to bigger code. Same for every language ever invented.

Amy B
  • 17,874
  • 12
  • 64
  • 83
  • I wanted to know what in Perl's syntax makes you able to do that – sak Apr 11 '10 at 12:41
  • Yeh... that's what I answered. – Amy B Apr 11 '10 at 12:44
  • 1
    @Coronatus: Not really. "code is transformed to bigger code" isn't a syntax property. – sepp2k Apr 11 '10 at 12:46
  • I mean *what* in Perl's syntax. Not *why*. E.g: Whitespace is optional, there is this construct that lets you do that, etc. – sak Apr 11 '10 at 12:46
  • Whitespace is optional in most languages. Python is one of the exceptions to that. – Quentin Apr 11 '10 at 12:48
  • 1
    What does this answer even mean? "copying a variable in only one line"? Are you referring to managing memory through garbage collected object references? "worrying about buses..."? Other than writing machine code for some devices, who does? "transformed to bigger code"? In what sense? – MtnViewMark Apr 13 '10 at 02:05