Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Beautiful Perl

by BrentDax (Hermit)
on Mar 26, 2005 at 11:57 UTC ( [id://442467]=perlquestion: print w/replies, xml ) Need Help??

BrentDax has asked for the wisdom of the Perl Monks concerning the following question:

The usual rationale for Perl's extreme syntactic flexibility is that, while it can lead to some truly hideous code (and utterly unreadable obfuscations), it also allows the clever programmer to write truly beautiful code.

I'm trying to illustrate this on the Perl page of a new version of my personal site (which I expect to be viewed mainly by experienced Internet users who haven't done any "programming" more complicated than HTML). Problem is, I'm not even sure where to look. So my question is, what beautiful Perl code have you seen? Suggestions should be for functioning code, not Perl poetry. For the purposes of the site, I'm hoping to find short snippets that read well to somebody who doesn't know Perl, but I'd also be interested to hear about cases where the beauty extends beyond the scope of a dozen or so lines.

--Brent Dax
There is no sig.

Replies are listed 'Best First'.
Re: Beautiful Perl
by tall_man (Parson) on Mar 26, 2005 at 14:01 UTC
    For me, beauty in a programming language is when an idea can be expressed simply and elegantly, doing something non-trivial in less lines than one would expect.

    The new Higher Order Perl book by Dominus has many good examples. There's a recursive Tower of Hanoi solver in about 15 lines, a directory walker with hooks to plug in your own functions, and many more examples.

    People who think perl is ugly have probably been using it as a slower C, instead of as the elegant, powerful language it is.

Re: Beautiful Perl
by bradcathey (Prior) on Mar 26, 2005 at 13:56 UTC

    "Beautiful," in referring to code, may be an overuse of the word. I prefer "readable." And it isn't only Perl code that can be readable. It can be any language. There are principles that apply to all making any bit of code readable and maintainable. And does it need to be maintained by you or others (though the way my memory is going, they are one in the same).

    Perl::Tidy is similar to other "tidying" programs, but I don't always agree with the author about what is tidy.

    I'd read the thousands of links out there on coding practices, Perl and otherwise (you'll often see Perl badgered for it's tendency to be poorly written).

    Then use those, plus a hybrid of what works for you and then stick to it (though I have altered certain stylistic practices once or twice in my coding career). Personally, I always try to write code that looks good on the page and that I can understand and fix months later. To write it so it is readable takes far less time than it takes to decipher poorly written code later.

    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot

      I don‘t always agree with the author about what is tidy.

      You can probably make it do what you want anyway. There are approximately seven and a half million options to control the output. My own .perltidyrc changes 14 of the the defaults, f.ex. It‘s still not just so – I still disagree with a few of its choices –, but that‘s so rarely an issue that it matters little in practice.

      Makeshifts last the longest.

      "Beautiful," in referring to code, may be an overuse of the word.
      I suspect that terminology got started with the "C Beautifier" cb.
      I don't always agree with the author about what is tidy.
      If the configuration options don't work for you, you can always hack the source code...
Re: Beautiful Perl
by tlm (Prior) on Mar 26, 2005 at 15:01 UTC

    The problem I see with this is that what the proficient Perl programmer may consider beautiful, may be impenetrable to the uninitiated. Consider this little gem posted by japhy:

    # randomize, via Fisher-Yates @array[-$i,$j] = @array[$j,-$i] while $j = rand(@array - $i), ++$i < @ +array;
    or the more pedestrian, but IMO very pretty:
    @no_repeats = do { my %h; grep !$h{$_}++, @with_repeats };
    Even Perl initiates freak out at stuff like this.

    So I don't know how much appreciation you will get from those that don't know Perl. But for those of us who do know some Perl, it will be quite a treat.

    the lowliest monk

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Beautiful Perl
by japhy (Canon) on Mar 26, 2005 at 18:17 UTC
    I'm trying to determine if by "beauty" you mean "idiomatic". That's what I think you mean, because you mention Perl's syntactic flexability.

    While others might find it ugly, I think code like

    select((select(FH), $|=1)[0]);
    is beautiful. It is a great example of lists, list slices, and using return values meaningfully.

    I think we should try to find Perl's equivalent of the Euler equation for mathematics. For those of you not familiar with it, it shows the relationship of five "basic" elements of mathematics: e (the natural logarithm), i (the square root of -1), pi (the ratio of a circle's circumference to its diameter), 1, and 0. The equation is e(i * pi) + 1 = 0. Does Perl have something like this? Something that shows a relationship between some of the building blocks of the language?

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
      If you were going for "relationship between some of the building blocks of the language", I'd have to advocate:

       open my $file, "name" or die "Error";

      While in no way profound, difficult or complex, I feel that it beautifuly demonstrates just what we like about perl. Or maybe not =].

      That's an interesting question, but first, what are the basic elements of Perl? The functions? The datatypes? The contexts? Control structures? If so, that's a tremendous amount of variability that could give rise to any number of "Euler equations".

      It seems unlikely to me that you could come up with a single comprehensive expression of the internal cohesiveness of a programming language. I think you'd either have to reduce it's components to more basic notions (for example, thinking of Perl's datastructures as variations of the list datatype), or generate some higher level principles using Perl. Notice that the elements of math that Euler was relating were precisely defined ideas expressed within the language of mathematics, not the language of mathematics itself, if that makes any sense.

      "The dead do not recognize context" -- Kai, Lexx
        I agree with your final statement there. The prospect of coming up with such a singular Perl statement is certainly a confusing and subjective one, but it would be interesting to see people produce comprehensive code and explain its beauty and significance.

        I think Perl's regex ease-of-use allows for its abuse, and in turn, some truly powerful and awesome and beautiful code, such as Abigail's prime number regex.

        Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
        How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Beautiful Perl
by cog (Parson) on Mar 26, 2005 at 12:53 UTC
    I would advise you to look into Perl::Tidy. It usually does a lot when it comes to "beautify" Perl.
Re: Beautiful Perl
by jhourcle (Prior) on Mar 27, 2005 at 03:33 UTC

    To me, beauty comes when I can accomplish something relatively easily. Of course, as do almost all of my work in Perl these days, I don't have those periods of struggling with something in {insert language name here}, and then switch back to Perl, and find that I can significantly reduce my number of lines of code (without significantly obfuscating it -- I'd rather have it be maintainable than be short ... of course, fewer number of steps tends to be more maintainable).

    You start to take for granted many of the more simple things. You tend to be impressed by the simple things that you just couldn't do (or couldn't do easily, or without extra steps), in whatever languages you learned before you got to Perl.

    For instance, someone who's only dealt with Perl, and other languages from its generation wouldn't fully appreciate:

    ($a, $b) = ($b, $a);


    foreach my $item ( @array ) { ... }

    or garbage collection. Or not needing to malloc all of your arrays. Or dealing with strings, without needing to worry about buffer overflows. Or strings longer than 255 characters.

    (Yes, I know, there are other languages that do this, but Perl was the first one I came across, and used it enough to be comfortable in.)

    PS. HTML is not "programming", with or without the quotes.

Re: Beautiful Perl
by polettix (Vicar) on Mar 26, 2005 at 19:10 UTC
    You're probably going to bore your visitors with any kind of beautiful code, whatever this means for you or anyone else. Why? Because they haven't done any "programming" more complicated than HTML, so what do you expect to be their taste in fact of programming beauty?

    My personal 2c would be showing them the Schwartzian Transform: marvelous, but not exactly what's readable for the newbie. But maybe all splendid Perl isn't immediately readable for the newbie, because (s)he is (at best) used to read and understand the basic control structures common to many languages, surely not some corners that make Perl an everyday discover (for me). Continuing on this line, any simple use of regex make Perl very attractive for texts, and beauty often means attractive :)

    But if I were you, given your expected audience, I would put this, which is probably the most beauty piece of code I've seen in years (and it keeps being beauty even when you de-obfuscate it :).


    Don't fool yourself.
Re: Beautiful Perl
by ambs (Pilgrim) on Mar 26, 2005 at 15:16 UTC
    You can't say "this code is beautiful". People can agree or not. There is not a concensus at all.

    Perl is a very flexive language. The main reason is because Larry studied linguistics. That means he know Natural language is flexible which makes texts easier (or not) to read. The truth is that two different people write the same idea on Natural language in two different ways. Perl is the same.

    Some example of linguistics constructions:

     open FILE, ">foo" or die "Can't open file foo\n";
     $a = 1 unless $a;
     print $a foreach @b;

    Hope this helps you out.

    Alberto Simões

      Actually ... you can say "this code is beautiful". You just (usually) cannot say it objectively. ;-) And, there is a lot of consensus on a lot of issues. Most of perlstyle is likely agreed to by most perl developers who have enough experience to tell the difference between readable ... and unmaintainable. By experience, I simply mean having to maintain code that is more than 6-12 months old, even if it is their own code.

      You can't say "this code is beautiful". People can agree or not. There is not a concensus at all.

      Yes, but this is true of practically any statement about aesthetics. Still, it doesn't stop people from building and visiting museums.

      the lowliest monk

Re: Beautiful Perl
by djantzen (Priest) on Mar 26, 2005 at 12:09 UTC

    Beauty is for the unemployed.

      I disagree. Try maintaining code which is bad for eyes and you'll see what I mean.

      And it's not a matter of spending more time coding because you're "beutifying" what you write. Don't tell me it is, because it ain't.

      You actually save coding time if you write it properly; otherwise, by line 20 or so you'll be wondering what the name of that variable was and you'll have a hard time finding it.

        Is beauty really just that which does not cause pain to look at ("bad for the eyes") or that reaches some minimum standard to be called "proper"? Is it efficiency? Is it brevity? Expressiveness? Self-documentation? Maintainability? Simplicity? Uniformity? Cleverness? All of these are identifiable as positive attributes, but is any one, or some combination, a sufficient definition of beautiful code? Still further, is it possible to evaluate the aesthetic appeal of code independent of the problem it is trying to solve?

        Aside from the fact that it's nearly impossible to get two people to agree on a standard of beauty, programmers are notoriously idiosyncratic, especially in as syntactically forgiving a language as Perl. Add to this the fact that the OP wants HTML authors to appreciate the allegedly beautiful code and you have an absurdity. You can show me the most finely-crafted, moving, subtle sentence ... in Turkish ... and I couldn't distinguish it from the drunken rantings scrawled on a bathroom stall. I don't know Turkish.

        Sorry to be a wet blanket (again), but this really is a futile exercise. If the intention is to demonstrate to people unfamiliar with Perl that it is a valuable language, show them how to solve problems with it. Show them what it can do, because they simply haven't got the necessary experience to appreciate whatever notion of beauty the code itself allegedly possesses.

        "The dead do not recognize context" -- Kai, Lexx

      I'd love to see your code review if you were on my team :) We have 7 guys all coding Perl at various levels of "Beauty".

      But they stick to some key rules for the sanity of the team:

      • comment often - I can scan comments a lot quicker than code to get to the bit I need to work on
      • indent 4 spaces - trivial, but helps a lot in terms of indentation expectations when reading nested stuff
      • use common code if it exists - just plain sensible
      • dereference using $var-> rather than $$var (it's just plain more readable)

      Of course, not everyone sticks to all these rules, all the time - and the times that they haven't have caused real pain (well, at least for item one on the list, especially on old code)

      Maybe you're old school - obscurity is job security. Wouldn't work here. If I can't drop into your code and scan a page in a couple of seconds and understand it, my job is harder, and your responsibilities would suddenly scale back ;-)

      Or maybe that's just me :)

      cLive ;-)

        Y'know, after turning thirty last Fall, being called Old School feels, well, kinda, oddly, amelioritive. <cheers>To being a curmudgeon</cheers>

        "The dead do not recognize context" -- Kai, Lexx

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://442467]
Approved by Corion
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-05-26 05:45 GMT
Find Nodes?
    Voting Booth?

    No recent polls found