Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Compactness

by FoxtrotUniform (Prior)
on Jan 11, 2002 at 02:30 UTC ( [id://137849]=perlmeditation: print w/replies, xml ) Need Help??

It just occurred to me that what I like most about Perl is the number of compact features and idioms that it makes available.

What originally got me hooked on Perl was its regular expressions: sure, they looked hairy to a beginner, and the more I find out about them, the hairier they look, but they're an excellent compact way of matching patterns, or pulling information out of a formatted string. What once took me 150 lines of (albiet non-optimal) C can now be done with 50 characters. Wow!

The next idiom to hit me like that was map and friends (join, grep, split, and so on). List operations that I'd originally spent dozens of lines on can now be done with just one or two. And don't get me started on the Schwartzian Transform.... Wow again!

Now I look at Perl 6, especially Apocalypse 3, and especially its hyper operators, and my hands start to twitch, and my eyes glaze a bit. And I write some Prolog, and I look at the binding operator, and the backtracking, and the other features that might make imperative Perl practical and worthwhile, and it looks even better.

This gives the impression that I really like compact, even golf-ish, constructs. I do, but that's not the point. I like being able to express myself tersely and easily, with a high ratio of semantics to syntax. (Writing featureful, functional code that makes other programmers grimace at its density is also kind of fun, of course.)

    Update: I should note that I don't (deliberately) write obscure production code. I'm well aware of my own limitations regarding understanding my own code three months (or days...) later, and I'm blessed with a few co-workers who are willing to comprehensively review my code. Those two things combine to keep my code from getting out of hand.

I'm sure that I've missed something: some other idiom that collapses many operations into something terse, compact, and expressive. That's one reason why I'm writing this meditation: to find out what I've missed. Another reason is to get a discussion going on compactness in Perl (and programming languages in general): do the benefits to an experienced programmer outweigh the hairiness involved? Thoughts?

--
:wq

Replies are listed 'Best First'.
(Ovid) Re: Compactness
by Ovid (Cardinal) on Jan 11, 2002 at 02:56 UTC

    A couple of favorite compact idioms:

    my %hash; # initialize all elements to 1 @hash{ @array } = (1) x @array; # assign empty string defaults $_ = "" for grep ! defined, ( $foo, $bar, $baz );

    Compactness can be a good thing, but it's important to not golf. 10 lines of code is easier to maintain then 50, but it's going to depend on the skill of the maintainer (who should, but might not, recognize for ( 1..10 ){}) and the quality of the code in question. Ten lines of code is terrible if it doesn't do any sanity checking (if necessary).

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re (tilly) 1: Compactness
by tilly (Archbishop) on Jan 11, 2002 at 04:13 UTC
    I believe that there is a strong correlation between understanding things well and having a compact mental model of them. As I touched on in Re (tilly) 3: Maintainable code is the best code -- principal components, this has implications for how good programmers organize code that is intended for other good programmers. (Less experienced programmers should be assumed to not be as fluent in building ideas on ideas. Therefore code written for their comprehension necessarily needs to be more repetitive. Remember the goal is communication of the model to a real human, and not some abstract ideal of programming.)

    Incidentally a couple of days ago I was talking to someone who is doing a PhD in neuro-science. In discussing what thinking is he brought up the same point. He said that the key characteristcs of the thinking process are the production of a compressed model from external stimuli, and then the utilization of that model for prediction. I found it interesting that people who officially study this stuff were thinking along similar lines to what I already suspected was important. That means that even if it is a strange-looking line of thought, it is at least a reasonable one to try...

    Anyways, yes. A shared vocabulary of compact idioms does help you communica^Wprogram well. They must be shared between programmers to work well, and certainly not all Perl programmers (not even all experienced ones) can be assumed to know the various corners of Perl. However I believe that the richness of Perl 5, and the greater coming richness of Perl 6, allows for a selection of a limited but highly effective "vocabulary" for the problem spaces most Perl programmers are likely to encounter.

      That tends to be a key feature of any expert field, I thought. Criticisms of most 'thought heavy' disciplines often involve a comment about the difficulty of understanding the (unnecessary) jargon.

      Practitioners often respond that the jargon is not unnecessary because it clearly and concisely expresses an idea that might otherwise take sentences to express. I think your idea applies well to any intellectual endevour where the ideas are more important than the way they are communicated.

      Larry's jokes about LZW compression of a language aren't really jokes when you think about it...

      Of course, you're thinking more of the mental structures that are being built to cope with ideas rather than the way they are expressed, but there are some (like myself) who believe that there isn't much difference between what a person says and does and who/what they actually are.

      Don't even get me started about my ideas on the way we treat everything in the real world as an object with defined interfaces... I'm taking an analogy a bit too far there.

      ____________________
      Jeremy
      I didn't believe in evil until I dated it.

Re: Compactness
by VSarkiss (Monsignor) on Jan 11, 2002 at 03:55 UTC

    It's not just terseness, it's also that the pieces in Perl fit together. In many other languages I use, I end up with clunky constructs because, for example, a particular statement doesn't evaluate its arguments, and there's no magic "yes, do it now" switch.

    Case in point: some code I wrote today has to rewrite a SQL template based on data returned from another query. I have to form a comma-separated list of the values in the first column of the result set, and I need to preserve the original template. (It's an SQL in clause; before I get brow-beaten, I should mention I'm working under "sociological" restrictions.)

    Here's what I wrote (paraphrased): ($sql = $templ) =~ s/#LIST#/join ',', map { $_->[0] } @res/e;It's not golf, it's just a nice fit.

    I'd be willing to type longer strings to get this, but the fact that I can feed map to join and use it on the RHS of a substitution makes me smile! I shudder to think what I'd have to do to achieve the same thing in, say, VBScript (to pick a particularly nasty example).

Re: Compactness
by dmmiller2k (Chaplain) on Jan 11, 2002 at 03:44 UTC

    Here's one of my own (recent) favorites, which is a variation on Ovid's initializing all elements of an hash to 1:

    my %column_num; my @column_lbls = qw( Id Name SSN Phone FAX ); # initialize a hash with an array index: @column_num{ @column_lbls } = 0 .. $#column_lbls; # to find the index of the item matching $col_name: my $index = $column_lbls{$col_name}; # to find the column numbers of several columns (e.g., a database quer +y): my @cols = @column_lbls{ qw(Name Phone FAX) };

    Update: Oh, and don't forget the Orcish Maneuver, another personal favorite.

    dmm

    You can give a man a fish and feed him for a day ...
    Or, you can
    teach him to fish and feed him for a lifetime

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://137849]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-19 22:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found