Reading someone else's (or sometimes our own) Perl code is not easy all time. One of the reasons is that, the code structure is different from person to person. For example, you can write
foreach (1..10) { print }
or
print for 1..10
Perl's TIMTOWTDI approach even allows you to use more and more code structures. If a particular code structure is followed, debugging programs etc could be much easier. This problem can easily be solved, if it is possible to identify and translate one code structure into another.

Programming requires building code-structures and within the limits of it, you are allowed to do different things. Different language offers different code structures. If there is a generic format available like XML for code, translating code structures would be very easy.

Till then, we need to study different code structures, the language provides and understand what is possible. It is an important tool towards the mastery of language. Studying more languages, helps in building more structures with Perl, given its flexibility. Which code structures you have identified in Perl and in other languages that you think, are in common practice or worthwhile to know?

--Artist

Replies are listed 'Best First'.
Re: Code Structures
by redhotpenguin (Deacon) on May 21, 2005 at 08:46 UTC
    A former coworker of mine gave me some invaluable advice with regards to coding when he said "I try not to do anything weird". That has helped me grow a lot as a programmer. After all, code is read more than it is written for the most part, right?

    When working as part of a team, you will be tasked with contributing to parts of the code which you are not familiar with. If you are a hobbyist who likes to decipher obfuscations, then maybe you prefer coworkers who can brilliantly transform a simple conditional into an elegant looking line of hieroglyphics.

    Now that I depend on reading and writing code for my livelihood, I prefer the simplest code structure that Gets the Job Done. Maintainability is key, and even though I work with smart people, I appreciate five lines of code with two lines of comments when perhaps the same task could be accomplished with one line of code and no comments.

    To paraphrase another former coworker who talked about issues he encountered when trying to implement a solution using map(), "Back in my day, we used foreach(), and we liked it!"

      I think this is why it IS important to know more ways to do something! Sometimes, one way of solving a problem quickly becomes a mess, when a different way would have been succinct, simple, and understandable. That's why it's important to learn different ways to do things. (In my opinion)

      -Bryan

Re: Code Structures
by mrborisguy (Hermit) on May 20, 2005 at 21:06 UTC

    I think everybody should try to identify and learn different code structures. However, in some cases you just can't use these all of the time. For example, at my last job, a college workstudy position, it's expected that the person who takes the job will have taken a few classes in Java, and that's all that can really be expected about their experience. In light of this, I often found myself programming in what I've heard referred to as "programming perl like programming c", or something like that. More relevant to my situation, programming perl like programming java. For most of the stuff I did, it probably could have been done better with a map, or a trailing for, or even something like a Schwarzian Transform, but I just didn't feel right using something like that, because I know that most of the students that will follow me won't really be too perl saavy. I should say I made this assumption by looking at the people who came before me, because their code looked alot like they only knew Java (but hey, maybe they just thought like I did).

    I guess that's just an example of sometimes being bound to a certain structure, even if you want to expand more!

    -Bryan

Re: Code Structures
by tlm (Prior) on May 21, 2005 at 15:18 UTC

    This is a very interesting topic, IMO. Perl has a reputation for being "write-only", and I think the root cause of this reputation is Perl's TIMTOWTDI philosophy, because it can result in each programmer having a very unique coding style. Perl is a huge everything-but-the-kitchen-sink language, and each programmer fashions his/her own personal lingo from it. This is great for the individual programmer, but I think it can lead to code that is difficult to read by others. Heck, I have problems reading my own code sometimes, because my coding style is constantly evolving.

    Consider this excerpt from the Second Exegesis:

    Perl has always offered the ability to code at your own level and in the style that suits you best.
    This sounds very reasonable and attractive, but it implicitly assumes that the only consideration when writing code is the programmer's comfort ("the style that suits you best"), which ignores the fact that programmers other than the original author may have to read, understand, and possibly refactor or (heaven forbid) debug the code. This too is part of the equation, and I would argue that for a large organization it is an important part of the equation; in the long run, a large organization prefers to own code that can be readily understood by any one of its programmers than code that shines for its Perlish erudition (but can be understood only by those few who have attained the author's level of expertise).

    I have often wondered whether in some more or less distant future Perl will spawn a much more limited and rigid dialect (ANSI Perl?) for the purpose of standardizing Perl programs. The impetus for this would be large organizations that want to use Perl but don't want a programming language that is so feature-rich that it takes years to master.

    the lowliest monk

      Perl has always offered the ability to code at your own level and in the style that suits you best.

      I think the bold part is something which for someone like myself is very important. Perl is a language that is relatively easy to start with. Using nothing more than perlintro and perlfunc a novice can start typing away and produce his/her first scripts. They may not look pretty or be the most efficient, but with a bit of effort they'll get the job done. When compared to the amount of basic knowledge one needs to even produce "hello world" in C or Java this is a huge asset.

      As for a more rigid dialect, I can't help but feel this highly depends on the circumstances. When seen in the context of a large organization I think it is this very organization itself that needs to manage which dialect is spoken throughout the project. Besides, Perl isn't the only language one can write horrible code in :-) In any case, long story short, any project involving more than 1 person needs to have some ground rules on how to work. My personal approach would be to create something like perlstyle, albeit more specific, and simply make sure everyone adheres to those rules. It's a lot easier to demand that people adapt their own styles to "the greater good" once there's paychecks backing up the arguments.


      Remember rule one...
      I very much agree with this assessment: I've made similar points in the past.

      I'm very much of the opinion that code should be written in the same structure as English: code should read much like prose. We learned English since birth, code is a relatively new development. Changing the rules just leads to confusion.

      We read left to right, to to bottom, in a single pass, and we parse sentences for meaning as we read. Unless there's a good reason to the contrary, program structures should follow the same patterns.

      This is why, for example, I consider foreach() clearer than map(). Linguisticly, foreach() is simpler.

      foreach() says, basically: set pronoun $_ to each of these nouns in turns, and then read the following sentences in the appropriate context. Children deal with pronoun substitution all the time. No problem.

      map() does the job backwards. We have first to read each of the sentences, abstract away the meaning of the pronoun $_ without knowing what it means, remember the meaning of the sentences, and then, at the end of the statement, take the memorized meaning of the abstracted sentences we've read, and substitute in each noun for the abstracted sentence. That's harder: we seldom do all that in English.

      Why is map() less clear? Well, because it breaks the familair linguistic rules of English. Specifically, it breaks the rule that says I can expect to know what a pronoun means before it's used. When that rule is broken in conversation, many people get confused. For me, the same trait carries over into coding; I'm more likely to get lost if I'm missing expected context.

      That distracts me from what I really want to understand: the hows and whys of what's been written, and specifically, why it's right, or what's gone wrong.

      As I've argued before, programming (in a professional context) should be considered akin to technical writing: a formally correct document that's transparently understandable to as wide an audience as possible. Writing obscure, beautiful poetry should not be the goal of a technical writer, nor of a professional coder: clarity, correctness, and simplicity should be the order of the day.

      Good coding, like good technical writing, is hard work. And like technical writing, it's easy to spot bad code, but harder to identify good code, except by contrast. I don't see the creation of ANSI Perl; Perl's strength as well as it's weakness is the richness of it's feature set. I see the creation of a myriad of fragmented in-house coding standards, and a lot of conflicting style guides.
      --
      Ytrew Q Uiop

Re: Code Structures
by Anonymous Monk on May 20, 2005 at 23:49 UTC
    If there is a generic format available like XML for code, translating code structures would be very easy.

    Actually, there's already a standard format, at least with Perl--the bytecode--though that doesn't matter so much. The same problem holds for any such representation.
    The problem with translating from some standard representation to different code structures is that there may be a large (perhaps infinte) number of structures that can be represented in the same way. This could be alleviated somewhat by expressing preferences of certain kinds of structures, but there's no guarentee that the produced code will be at all readable. Conversely, there are highly similar code structures that may be represented in vastly different ways.
    You also have to consider different definitions of "code structure". Is the way I choose to factor code into subs a structure? If I determine odd-ness with $foo & 1 and you do it with $foo % 2, is that a translatable code structure? This falls apart particularly in the face of operator overloading, in which there's no way to determine semantic equivalence of % 2 and ^ 1.
    Language translation is hard, even if you're starting and ending in the same language.

Re: Code Structures
by jjohhn (Scribe) on May 22, 2005 at 03:00 UTC
    two things:

    I read an essay about Eclipse (the java IDE) that described Eclipse as moving toward more explicit representation of the deep structure ("code structure") of a program.

    Internally it does represent these things to itself, which is how it knows how to refactor code in the various ways it does. In other words, it could be said to be parsing the source at a deeper level than just the surface syntax.

    There might be something in the Eclipse community that resonates with what you are describing.

      You can already do something of the sort with PPI, but the problem is that the conventions for classes and many other "simple" things in Perl 5 make it less useful than with 'rigid' languages like Haskell, Java, etc.

      autrijus is one notable happy user of eclipse, when he's not using vim.

      This level of introspection, making it "easy" to edit Perl with refactoring editors is one of the goals of Perl 6.

      $h=$ENV{HOME};my@q=split/\n\n/,`cat $h/.quotes`;$s="$h/." ."signature";$t=`cat $s`;print$t,"\n",$q[rand($#q)],"\n";
Re: Code Structures
by TedPride (Priest) on May 21, 2005 at 17:41 UTC
    Perl code varies a fair bit, but there aren't really that many differences from C-based languages. What sets Perl apart is not its structure - though there are a number of shortcuts available for structure - but rather its system of environment and input / output variables. Those allow you a lot of power and flexibility with very short, difficult to read code. Learn the variables and you've pretty much learned Perl.
Re: Code Structures
by Jenda (Abbot) on May 24, 2005 at 16:49 UTC

    Yes, you may force all your programmers to use only the part of the language that the dumbest or least experienced of them knows at that time. You should not be surprised if their productivity decreases to match that dumbest or least experienced one's as well.

    Jenda
    XML sucks. Badly. SOAP on the other hand is the most powerfull vacuum pump ever invented.