How I Comment Perl Code

I realized a few days ago that I have a particular way of commenting my Perl code. I wonder if I’m unique in this way, or if these are habits I’ve picked up reading others’ code over the years.

A documentation command is prefixed by two hashes (##) followed by a single space and indented to the level that matches the code:

    ## this loop iterates over each foo item to compute bar

A line or block of code that’s being commented out for the long-term (such as extra debugging that I might only turn on once in a blue boon) is prefixed by a single hash (#) followed by a single space and indented to the appropriate level.

    # if ($foo->validateIndex()) {
    #     print STDERR "blah!";
    # }

A line or block of code that’s temporarily commented out and expected to be turned back on soon is prefixed by a single hash (#) with no space to separate it from the code itself. Often times it’s not indented appropriately either.

    #unlink $tmpfile or die "unlink: $!";

What commenting habits do you have?

About Jeremy Zawodny

I'm a software engineer and pilot. I work at craigslist by day, hacking on various bits of back-end software and data systems. As a pilot, I fly Glastar N97BM, Just AirCraft SuperSTOL N119AM, Bonanza N200TE, and high performance gliders in the northern California and Nevada area. I'm also the original author of "High Performance MySQL" published by O'Reilly Media. I still speak at conferences and user groups on occasion.
This entry was posted in programming, tech. Bookmark the permalink.

20 Responses to How I Comment Perl Code

  1. Glen says:

    My personal method is similar;


    ### this implies long term documentation


    # this implies code commented out for long term


    #this implies testing code

    The reason for the 3 hashes is because of Damien Conway’s Smart::Comments. They make for nice debugging comments inline.

  2. Dan Weinreb says:

    Well, I don’t do Perl, but in case it helps you in any way, the standard for Common Lisp is:

    “;;; xxx” at the beginning of a line means a comment about the top-level form following, e.g. a whole function. Not to be confused with the doc-string, which is where you put the actual contract to the caller; the comment is to talk about other stuff like implementation details, history, plans, etc.

    “;; xxx” These are aligned with the code and generally refer to the following form, which is indented the same as the semicolons.

    “;xxx” is used after some code, on the same line. Only useful for very short comments, otherwise the “;;” form is best. Rarely used.

    #| …….. |# is how you comment out code. By convention, these are
    put on the line before and line after a section, rather than in among the stuff being commented out. And for some reason we all do #|| and ||#, which is the same thing since the vertical bars are part of what’s commented out.

    If you want to conditionally “comment out” some code based on a parameter that can be controlled at compile time, you use #+feature
    or #-feature. The following form will be seen or not seen based on whether the specified feature is present or absent. A “form”, in Lisp, can be a whole definition, or any expression (there is no concept of ‘statement’; they are the same as expressions).

  3. /* Documentation.  Sometimes
     * there is a lot.
     */
    void foo(void) {
    
    	/* Implementation details, always prefixed by a newline. */
    	code();
    
    	/* Again, with the vertical space. */
    	code();
    
    /* But temporary debugging blocks stays at the left margin. */
    /*
    if (DEBUG) {
    	code();
    }
    */
    
    }
  4. NJDEBUG says:

    1. I break my method up using slash slash and 80 stars, always 80, it is like a sharp cut line across the code and makes the methods easier to see.

    //*************************************************************

    2. I use {} to group blocks on code according to the comments, so {} may group an ‘if’ statement, or a ‘while’ loop, but it may just group a block of code according to a comment.

    // Draw the time of day
    {
    …. some drawing code all related to time of day
    }
    // Draw the weather that day
    {
    ….. weather drawing code and any temp vars
    }

    //*************************************************************

    3. I use lots of comments, everywhere, all the time, even when I’m sure I don’t need them, because I’m an idiot today and tomorrow I’m a genius, or is it the other way around? The comments reveal all.

    //*************************************************************

    4. I use // NJDEBUG if the change is only for debugging, if there is one of these in an end product, it is an error.

    4a. As with Richard, temporary code is at the left margin so it looks odd and stands out.

    4b. As with Richard, new lines bind the comment to block of code it is associated with, and usually the line is at the top of the block.

    //*************************************************************

    5. During late phases of development, I remove blocks on code that have been commented out for a long time as gone for good. I call it code cleanup, but I view it more like ‘setting’ the change into stone.

  5. NJDEBUG says:

    “Leave a Reply Cancel reply Your email address will not be published”

    I see you have the patterned Swatch on my comment, I notice it is the same pattern swatch where-ever I use the same email address, presumably a WordPress script feature.

    I’m posting this to see if the same swatch appears using a different email address.

  6. NJDEBUG says:

    And how much does the swatch change based on a single letter change to an email address.
    (Another test comment)

  7. NJDEBUG says:

    Gravatar.com, MD5 on my email address it seems with enough resolution to uniquely distinguish each email address.

    Jeremy, I’m not sure thats a good idea to use those:
    If I had a spammers list of email addresses, I could mine the web and match those email addresses to comments effectively removing any anonymity you offered the submitter of those comments.

  8. Brett Tabke says:

    I rarely comment any more. I used to be comment junkie, but I have so much code running now, that “big picture” comments at the top of the file.

    Coming from assembler, I am a subroutine and command loop junkie. Everything is deeply structured. I use longer-than-normal and highly descriptive subroutine names. Such as:

    sub PrintBlogCommnetsNoReturns

    I find it cut down my comments considerably over time.

    When I do comment:
    I use 3 hashs to comment out code I want to keep. ###
    I use a hash and dashes #—— to mark the start of big code blocks or big subroutine blocks. I also use #- to act a flag for my editor. I created a kb macro to search for the #- makers for quick finding of blocks.

  9. Andrew S says:

    I mark major sections with a comment rectangle:

    ###########
    # Perldoc #
    ###########

  10. Jorge Grippo says:

    I mostly use three formats. More important one is the second:


    #
    # three lines for headings
    #

    # http://dev.mysql.com/doc/bla.
    my $query = "SELECT MATCH( ...

    # print "temporary commenting\n" if DEBUG;

    Storing the url from an important hint, blog article, documentation, is the most useful reason to comment in code. It would be nice to have C style commenting, but … we haven’t. I consider C commenting more elegant.

  11. Dan Weinreb says:

    I want to add something to my previous comment, above. Full disclosure: I am NOT a Perl programmer, so my perspectives might differ.

    I once joined a small software company, and was given the task of
    adding some features to an existing Perl program. When I approach a
    new body of software, the first thing I do is to draw a simple picture
    of the data structures (or objects, as the case may be). Then I draw
    arrows between them, showing things like one-to-many or many-to-many,
    in a simplified UML diagram.

    In Java (or CLOS), you can look at the declarations of classes to find
    out the instance variables (or slots, respectively) very easily.

    But since Perl allows you to add new instance variables on the fly,
    the only way for me to construct my diagrem was to read every single
    line of executable code. This is a LOT of work.

    Perl’s flexibility here perhaps can be of genuine benefit. But in the
    program I was looking at, I was not able to see any reason that this
    was necessary.

    My foremost suggestion for Perl style is to create all the instance
    variables right up front and not create any more.

  12. Dan Weinreb says:

    Here are comments on the above comments.
    Richard Crowley: Your example included this:

    /* Implementation details, always prefixed by a newline. */
    code();

    Without seeing more about “code();”, it’s hard to tell, but usually,
    if I were to put a comment in that syntactic place, it would not be to
    explain implementation details. It would say WHAT the code does,
    rather than HOW. On the other hand, you can always say that if you
    have some code where the what/how relationship is interesting and
    non-obvious enough to justify a WHAT comment, you should factor that
    into its own function/method, and put the WHAT comment at the top of
    that function/method.

    In any case, being consistent with your style, especially among the
    whole development team, is very important. In some respects it’s even
    more important than which style rules you pick, as long as those rules
    are drawn from the set of alternatives that make sense.

    NJDEBUG, point 2: Putting in extra {}’s to clarify the scope of a
    comment is a great idea. In Common Lisp, what with all the parens,
    there’s usually already grouping for that purpose. Speaking as an old
    fogy, I’ll point out that your {}’s remind me of blocks in Algol
    60. That’s an ancient programming language but it was cutting-edge in
    its day, and many of its features have heavily influenced the
    languages we use now. (That’s true of Lisp as well but that’s another
    story.)

    NDEBUG, point 3: That’s fine as long as you don’t put in useless
    comments like:

    /* Add 5 to a. */
    a = a + 5;

    Strangely enough, I come across these even in code written by
    otherwise fine engineers. In this case, if there’s going to be a
    comment, it should add value by explaining why adding 5 to a is a good
    thing to do at this point, and what it means.

    Writing comments is a pedagogical activity, sharing the same essence
    as writing a technical manual or teaching a technical course. Of
    course comments are quite different from those things, but they share
    the important property that you must characterize your target
    audience, and take into account what they already know and what they
    don’t know.

    NDEBUG, point 4: We use a convention of putting “;; +++” or “;; —” to
    indicate that this code is known to be a workaround that ought to be
    fixed, or that it is questionable and should be re-examined. That makes these easy to recognize n cases and to search for.

    NDEBUG, point 4a: I disagree; code should always be indented properly,
    or else it’s very hard to read. This is very important in any
    Lisp/Scheme dialect, and in Python it’s completely crucial. Maybe
    this makes more sense in Perl than in other languages.

    Brett Tabke: I completely agree about descriptive names.
    It’s interesting that so many people want very concise
    code. People who like Ruby and compare it to Lisp
    love to show how short their code is, and a lot of it is
    because Ruby’s built-in methods have such short names.

    One could argue that it’s OK for built-in ones to have short names and
    for user-defined ones to have long names. In Lisp, it is anathema to
    make “system/user” distinctions. The same rules apply for both, to
    the point where the dichotomy hardly matters. But Lisp is different;
    it’s a long story.

  13. tanguy says:

    For me, I use very long lines :

    ###########################################
    #### Explainations

    # It is more simple to understand everything, but it is maybe a little heavy.

  14. NDEBUG says:

    @Dan, “NDEBUG, point 4a: I disagree; code should always be indented properly, or else it’s very hard to read.”

    But it *is* properly indented, it’s temporary or debug code and thus the indent needs to show it’s transient or special nature….

  15. Dan Weinreb says:

    I did not realize that by “properly” you meant “the way I think it ought to be indented”, since that seems to be a tautology. When I say “properly”, what I mean is more like “what the automatic indentation command in the IDE does.” So, what I was saying is that I would not use the convention of left-aligning temporary code. I would mark it prominently as being temporary, but in some other way. Otherwise, the meaning of the code might be harder for a reader of the code to understand.

  16. maurice says:

    my perl comments still look rather FORTAN’y

    with major comments looking like this
    #
    # — extract terms from returned xml trying Randl’s sugestion of using a html parser and not the shite xml modules!
    #
    I do like trailing comments if want to comment on what a particular line does (usefull for reminding your slef what aparticularly crufty regex does.

    And if I eaver wanted use a GOTO I might even revert to using old sckool lables like 6010, the 7000 and 8000 range being reserved for FORMAT Statements of course.

  17. Steve says:

    For debugging that you turn on and off occasionally, this is much better and avoids using comments for them:

    my $debug = 1;

    …later…

    $debug && print $something_interesting;

    Other than that, I’m part of the “one line for small comments —

    # mumble whatever
    $x = something_clever_here;
    — and three lines for blocks —

    #
    # This next bit adjusts the frobnitz when the kooglehammer rises:
    #

    — crowd”.

    …Steve

  18. Jesenia says:

    Appreciating the commitment you put into your site and detailed
    information you offer. It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed information. Wonderful read!
    I’ve bookmarked your site and I’m including
    your RSS feeds to my Google account.

  19. Stacy says:

    Fantastic goods fdom you, man. I have take into account your
    stuff prio to and you are just extremely wonderful.

    I actuallly like what you’ve bought right here, certainly like
    what you’re saying and the way in which wherein you are saying it.
    You make it entertauning and youu still take care of to keep it sensible.
    I cant waikt to read farr more from you. That is really a terriific site.

  20. Mahadev says:

    Multi-line comments emulation in Perl. Use POD. For example, you could use: =for comment Commented text =cut. Any decent editor should allow you to put a # in front of n lines easily

Leave a Reply to maurice Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s