Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Multi-line comments in perl code?

by mrguy123 (Hermit)
on Jul 13, 2006 at 12:32 UTC ( [id://560924]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks. Does anyone know if I can write comments in Perl without opening each line with #. For example, I would like not to have to type "#" 4 times in the following code:
$paramData = &replaceParamsInString($self->{debug},$contentRequest,$pa +ramsMLToRequest); #A hash named $requestParams is created containing all #the data needed for the http transaction. This data #is then stored in $self->RequestParams, and no further data # is needed. my $requestParams = $self->{RequestParams}; $requestParams->{cgi_method} = $self->{method}; $requestParams->{url} = $self->{Find}->{baseUrl}; $requestParams->{httpContent} = $paramData;
I know that in Java you can place a */ or something similar at the beginning and end of the comments, and then not have to start each new sentence with a star. Is there something similar in Perl?
Thanks in advance,
Guy Naamati

2006-07-14 Retitled by Steve_p, as per Monastery guidelines
Original title: 'Perl documentation'

Replies are listed 'Best First'.
Re: Multi-line comments in perl code?
by rodion (Chaplain) on Jul 13, 2006 at 15:34 UTC
    I think it's useful to boil down what's already been said or referred to.
    • POD is the official way to do multi line comments in Perl, whether you think of it as as a work-around or not (which varies),
    • use "=for comment" or "=begin/end comment" for stuff that's just comments and shouldn't show up in the output text when documentation is extracted from the code, such as when you run perldoc on the program,
    • You can't indent the "=for comment", so it's not quite like other language's multiline comments, and
    • You do need a "=cut" at the end to get back to code. (I think this might be your main objection to using POD, and, yes, you're stuck with it).
    The last item may change with Perl6, for "=begin/end", but the rest will probably not. See Apocalypse 2 RFC 5

    Here's an example which you can runn with "perl" and with "perldoc" to see what shows up where. Note that in many places, such as before the "=cut", the blank line is part of the syntax.

      The last item may change with Perl6, for "=begin/end", but the rest will probably not.
      Actually, the first point:
      POD is the official way to do multi line comments in Perl
      will also change in Perl 6, which introduces an indentable, nestable, multi-line-able delimited comment:
      #{ comment here } #[ comment here ] #( comment here ) #< comment here > #« comment etc. »
      A delimited comment is introduced by a # followed immediately by any kind of opening bracket. It is closed by the corresponding closing bracket.

        Ow. Would it be too much to ask that it accept any sequence of openingbrackets — e.g.

        #<<<
        #<{[
        
        because I could easily see myself wanting to comment out blocks of code with unbalanced closing brackets of all four types (or, more to the point, a dynamic selection of closing bracket types). Having an unlimited variety of comment "identifiers" also facilitates arbitrarily nesting comments without artificial restrictions.

        We're building the house of the future together.

        Yay!++


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
      Also you can always look at another Perl module and see how they document their code :)
      To clarify: as of writing, on Perl 5.28.1 and Perldoc v3.2801:
      • =for comment hides text from perl but not perldoc
      • =begin comment hides text from both perl and perldoc
      For example, given foo.pl as follows:
      =head1 SECTION =for comment Comment! =cut =begin comment Comment! Number 2 =end comment =cut
      • perl foo.pl produces empty output and no errors
      • perldoc foo.pl produces:
        SECTION Comment!

        which is the text from the =for comment / =cut block.
      Therefore, I personally use =begin comment / =end comment / =cut, even though it's a bit tedious.
        =for comment Comment! =cut
        ... produces:
        SECTION Comment!

        That is the correct behavior, your conclusion "=for comment hides text from perl but not perldoc" isn't correct. From perlpod (emphasis mine):

        The command "=for formatname text..." specifies that the remainder of just this paragraph (starting right after formatname) is in that special format.

        Remove the blank line after the =for and the "Comment!" is hidden. The =for still begins a section of POD that needs to be terminated by =cut, so Perl will ignore the entire example you posted.

      It seems that the '=begin comment'/'=end comment' pair doesn't work inside of if-blocks, does anyone know if there is a fix for it?

      E.g. the following code will fail to compile with a 'missing right curly' syntax error.

      if(1==1) { =begin comment print "something else\n"; =end comment print "hello!\n"; }
        You're missing a "=cut" to end the POD.
Re: Multi-line comments in perl code?
by McDarren (Abbot) on Jul 13, 2006 at 12:42 UTC
    There is no "official" way to comment out large chunks of code in Perl, although there are plenty of workarounds. Generally, it depends on which editor you are using. Any decent editor will allow you to define a macro or hotkey for this purpose.

    One method that some people use is to make use of pod-style =pod and =cut.

    Cheers,
    Darren :)

      Thanks Darren.
      I understand that perlpod is a very powerful tool for documenting a program so that you can create a html documentation page. It is a very good way to write comments before the function begins. I was wondering if there was a different way to write long comments inside functions with out using =pod and =cut, and obviously without starting each new sentence with a "#".
      Thanks again,
      Guy

        I assume that you're worried that "pod comments" will appear in the output from any POD processing that you do on the file. The way round that is to use the =begin and =end directives. Any section that is marked as =begin comment will only be picked up by a POD processor that is specifically looking for content marked as a comment. No such processors (currently) exist, so your comments wouldn't suddenly start appearing in your documentation.

        See perlpod for details.

        --
        <http://dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg

        Okay, well again the answer is "No, not really"
        But that doesn't mean you can't automate the task. For example, if you happen to be using Vim as your editor-of-choice, then there is a very useful BlockComment plugin available, which makes this task very easy.

        Cheers,
        Darren :)

Re: Multi-line comments in perl code?
by dimar (Curate) on Jul 13, 2006 at 15:20 UTC

    The feature about which you inquire is customarily referred to as Multi-Line Comments. Perl does not have this feature. That is, it does not unless you resort to a source code filter, an add-on module or any of various klunky 'workarounds' which may or may not be suitable for your needs.

    It is important to emphasize that POD is *not* the same thing as Multi-Line Comments. At least not if you are accustomed to the CPlusPlus/Java variant. Among other things, POD does not support indentation, and POD does not support "comments" that span fewer than two lines.

    It may be more productive to simply acknowledge that perl does not have this feature, and consider the alternatives, such as a script or macro for your text editor, rather than try to shoehorn them in, and bother with potential side-effects.



    =oQDlNWYsBHI5JXZ2VGIulGIlJXYgQkUPxEIlhGdgY2bgMXZ5VGIlhGV
      Among other things, POD does not support indentation

      Sure it does -- in a Pod format block.

      =begin someformat This comment can be indented as much as I want =end someformat =cut

      That said, I agree otherwise with your point that Perl doesn't support multi-line comments. Pod can be used for multi-line comments, but Perl and Pod are really two separate languages that can live in the same file. The Perl parser and Pod parsers just choose to pay attention to different languages.

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        Among other things, POD does not support indentation
        Sure it does -- in a Pod format block.

        Perhaps, but that particular definition of "indentation" is ... shall we say, a lot more 'loose' than the originally intended definition, which can be illustrated as follows:

        =for comment This comment can be indented as much as I want and even more than I want =cut for(0 .. 4){ for(0 .. 3){ for (0 .. 2){ =for comment However, even though "indentation" is supported here, we still have those dangling POD delimiters way back over there. <- <- <- <- Attempting to line them up with the rest of the code produces an error. This is not good because it breaks 'code-folding' in the text editor. It also looks just plain ugly. =cut print "$_\n"; }; }; }; __END__

        Moreover, one has to consider whether the POD in this illustration is even well-formed to begin with. Should this be a format block? Will begin/end work? Is 'for comment' sufficient? Will this mess up the POD documentation? *Way* too much hassle when all you wanted was a *comment*.

Re: Multi-line comments in perl code?
by ikegami (Patriarch) on Jul 14, 2006 at 19:28 UTC
    Analysis of Solutions (Yes = good)
    Solution Optimized away Strict friendly Indentable directives Usable mid-statement
    my $comment = <<'EOC'; bla bla EOC
    No Yes No No
    $comment = <<'EOC' if 0; bla bla EOC
    Yes No* No No
    0 && <<'EOC'; bla bla EOC
    Yes Yes No No
    0 && q{ ... };
    (and variations)
    Yes Yes Yes No
    =for comment bla bla =cut
    Yes Yes No Yes
    # bla bla # bla bla # bla bla
    Yes Yes Yes Yes

    Judgements on readability left to you.

    None of the above give warnings.

    * — One cannot simply add my because the behaviour or my ... if 0; is undefined, and thus must not be used.

Re: Multi-line comments in perl code?
by madtoperl (Hermit) on Jul 13, 2006 at 12:41 UTC
    Hi mrguy123,

    Yes, you can.see you have to give some name and end with cut.Eg.
    =comment A hash named $requestParams is created containing all the data needed for the http transaction. This data is then stored in $self->RequestParams, and no further data is needed. =cut
    Thanks and Regards,
    madtoperl

      Even though the Perl parser sees that as Pod and ignores it, it's important to advise people that it's not proper Pod and may behave unexpectedly with some Pod parsers now or in the future. For a single paragraph (no blank lines), a Pod =for directive would work as well (though with slightly more to type.)

      =for comment A hash named $requestParams is created containing all the data needed for the http transaction. This data is then stored in $self->RequestParams, and no further data is needed. =cut

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        Thanks a ton :) I am a beginner in Perl and i use a lot of comments while learning how to use Perl.It was easy in java to add comments. But in Perl i didn't know how to add multi-lined comments. Thanks again!
      Thanks it really helped a lot
Re: Multi-line comments in perl code?
by CountZero (Bishop) on Jul 13, 2006 at 19:31 UTC
    TIMTOWTDI!
    $comment = <<'EOC' This is a multiline comment. You can even indent it! Look And come back To the margin. EOC
    Of course the word comment is used here in its widest sense.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

      Such an assignment has to end somewhere (semicolon, block end, EOF) to be syntactically correct.

      For sake of simplicity, assuming it is really just a comment (as opposed to production data), right on the same line, as in

      $comment = <<'EOC'; bla bla EOC

      And while you are on it you can even give perl a hint that it can forget about that content as soon as possible:

      $comment = <<'EOC' if 0;

      Of course, whether you should resort to such "comments" is a completely different question.

      Your solution

      • is not strict-safe, but that can be fixed with a my
      • is not optimized away,
      • doesn't have indentable directives.

      The following doesn't suffer from those limitations:

      0 && q{ ... };
      0 && comment && q{ ... };
      use constant _comment_ => 0; _comment_ && q{ ... };
Re: Multi-line comments in perl code?
by tcf03 (Deacon) on Jul 13, 2006 at 20:03 UTC
    if you use vim add the following to your .vimrc
    set formatoptions=r
    after your initial # comment goes here - each time you hit a newline, a # will be placed at the beginning... or/and to .vimrc
    " comment out blocks " ma to mark beginning " put cursor at the end and hit F7 " code will be commented out map <F7> :'a,.s/^/#/gi^M:nohl^M map <F10> :'a,.s/^#//gi^M:nohl^M
    I believe I got that last one from a thread here...

    Ted
    --
    "That which we persist in doing becomes easier, not that the task itself has become easier, but that our ability to perform it has improved."
      --Ralph Waldo Emerson
      I use a variant of that approach for Vim. In my .vimrc file:
      "=====[ Add or subtract comments ]=============================== function ToggleComment () let currline = getline(".") if currline =~ '^#' s/^#// else s/^/#/ endif endfunction map <silent> # :call ToggleComment()<CR>j0
      Thereafter hitting # in Normal mode either inserts a comment marker(if the line doesn't have one) or removes it (if one was already there). Either way, the cursor is then moved to the next line ready to dish out more of the same treatment.

      The upshot is that a series of #'s runs you down the file, toggling the commentedness of each line.

      However, for inserting/removing long blocks of comments I find Visual mode the easiest solution. Navigate to the start of the first (or last) line on which you want to insert comments. Then type CTRL-V to enter Visual Block mode. Then navigate to the other end of the block of code you want to comment, using any of the normal Vim motion commands. Then type I#<ESC> and...voilą!

      To subsequently remove a block of column-1 comments: CTRL-V(navigate to other end)x

      UPDATE: Added missing if line and corrected else (thanks Jack!)

Re: Multi-line comments in perl code?
by Steve_p (Priest) on Jul 14, 2006 at 02:53 UTC

    While pod comments do work, its not especially recommended, and they may be removed in the future. From perlsyn...

    Note that pod translators should look at only paragraphs beginning with a pod directive (it makes parsing easier), whereas the compiler actually knows to look for pod escapes even in the middle of a paragraph. This means that the following secret stuff will be ignored by both the compiler and the translators. $a=3; =secret stuff warn "Neither POD nor CODE!?" =cut back print "got $a\n"; You probably shouldn't rely upon the warn() being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier.
Re: Multi-line comments in perl code?
by Anonymous Monk on Jul 13, 2006 at 19:28 UTC
    I know that in Java you can place a */ or something similar at the beginning and end of the comments, and then not have to start each new sentence with a star.

    The first thing to realize is that you don't have to type a hash at the start of every line. (You used the word "star", but a star is this symbol: "*". A "hash" or a "pound sign" is this symbol: "#". Just so you know... :-) )

    Any decent editor (and quite a few bad ones) will let you comment a block without really thinking about it. The trick is, finding an editor that you're used to. I don't really recommend learning vi (it's horrible to learn), but once you know it, things work almost without any concious effort.

    For example, using vi, I do this, pretty much by reflex:

    1. type "ma" (mark current line as "a")
    2. hit "i" for insert mode, then type my comment
    3. hit "ESC" (to exit insert mode)
    4. type "mb" (to mark the new line (the end of the comment) as "b")
    5. type ":'a,'bs/^/#/" (from line a to line b, match at the start of line, and substitute in a hash )
    6. type ":'a,'b>" (optional: indent one level, add more > symbols to indent more)

    You can do pretty much the same thing in Emacs, or any other editor you like.

    Good luck! :-)

      even easier in vims visual block mode. <CTRL>+v, mark the lines you want to comment, type I, type #, type <ESC>.
Re: Multi-line comments in perl code?
by loris (Hermit) on Jul 14, 2006 at 08:19 UTC

    Hello mrguy123,

    With emacs you can do

    # A long comment which I would rather have on multiple lines

    and then do

    M-x fill-paragraph

    (which is often bound to M-q) to automagically get

    # A long comment which I would rather # have on multiple lines

    the position of the line break depending on the setting of the variable fill-column.

    So spend a few days (months, years, ...) getting your head round emacs and (then) have fun.

    loris


    "It took Loris ten minutes to eat a satsuma . . . twenty minutes to get from one end of his branch to the other . . . and an hour to scratch his bottom. But Slow Loris didn't care. He had a secret . . ."
      Does this car have a handbrake?

      No, but if you keep pressing the footbrake it won't go anywhere.

      But isn't there an easier way of stopping it from rolling away on inclines?

      Well. If you buy an 18-wheel semi-trailer truck, learn how to drive it with it's 10 gears & hi-lo ratio shifts, and arrange to park it wherever you want to stop in your car; then if you park your car uphill from it, it won't roll very far.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        C-u BrowserUk M-x detect-believer-in-the-one-true-editor No believer-in-the-one-true-editor 'BrowserUk' found (you can run this + command with 'C-g C-r C-o C-w M-n M-e M-w C-d C-i C-g C-i C-t)

        loris


        "It took Loris ten minutes to eat a satsuma . . . twenty minutes to get from one end of his branch to the other . . . and an hour to scratch his bottom. But Slow Loris didn't care. He had a secret . . ."
      Hi loris.
      I have used emacs quite a lot in the past (a few years actually), and had quite a comfortable time with many things (including comments). Since then I have moved to a company where vi is the standard, and although it took me a while to get used to it (what in the %$!* is escape mode?) I eventually managed to regain all my old editing tools along with a few new ones (":s 1,25" is usually enough to comment out lines 1-25). What my question was (and after a lengthy discussion I assume that the answer is no) is whether I can write multi-line comments in Perl without perlpod. Although the answer is negative, I have learned about a few new tools that can make comments easier.
      Thanks for your good advice,
      mrguy123
      Emacs also has a "ESC x comment-region" command (which I have bound to a key, myself). Select the block of multi-line text, do a comment-region, and in cperl-mode, "# " will magically appear in front of every line. If you do a "C-u" prefix first, you can use the same command to remove the commenting.

      Alternately, it's not at all difficult to write keystroke macros that do things like "insert a '#' in front of this line and then move down one line", which you can loop to comment a series of lines.

      The default keystrokes for that (Off the top of my head, and untested):

      Defining the macro:

      C-x ( C-a # C-n C-x )
      Running it once:

      C-x e
      Running it 10 times:

      C-u 10 C-x e

      My personal preference: don't use one of the workarounds. Everyone understands "#" commented lines, but many will find your workaround confusing. Optimize for readability, not for ease of typing.

      But if you do use a workaround, my preference would be for abusing pod ('=for comment/=cut'), which is endorsed by Damien Conway in "Perl Best Practices".

Re: Multi-line comments in perl code?
by wazoox (Prior) on Jul 14, 2006 at 21:32 UTC
    I have in my editor ( NEdit) a very convenient macro : I select any number of lines then hit Alt+q, and the whole selection is commented out. I select any number of commented lines (or not, it doesn't matter actually) and hit Shift+Alt+q and the selection is uncommented.
    I think such macros are extremely easy to program with any serious editor, and even comes included in many. That makes multi-line comments of little interest IMO.
Re: Multi-line comments in perl code?
by Moron (Curate) on Jul 14, 2006 at 13:34 UTC
    You could plan to run all your Perl sources through the C preprocessor before further use and that way co-opt its functionality. The added benefit is that you can then use all of the C preproprocessor functionality, e.g. macros, defined pre-execution symbols and so on in your Perl code - in fact this particular usage pales into triviality compared with what then becomes possible for projects with complex implementation and/or porting requirements.
    #!/usr/bin/perl #IFDEF COMMENT #+++ I am a comment - symbol COMMENT is left undefined So there Instructions: this file is called fred.plp and should be run through the C preprocessor with output to fred.pl - modules could be presourced with the extension .pmp #--- #ENDIF my $x = 1; open my $fh, '<fred'; # etc. __END__

    -M

    Free your mind

      You could plan to run all your Perl sources through the C preprocessor before further use

      There's even a command line option (-P) which does just that. Tho' it has to be pointed out that the docs say "Use of -P is strongly discouraged because of its inherent problems, including poor portability".

      --
      <http://dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

Re: Multi-line comments in perl code?
by j1n3l0 (Friar) on Jul 14, 2006 at 18:20 UTC
    you can always stick it in a "pod". i know thats not what they're for but it does work. eg
    =sub name: print_stuff desc: this subroutine prints stuff! =cut sub print_stuff { print 'stuff' . "\n"; }
    failling that u can always use epic plugin on eclipse or komodo IDE to comment out multiple lines in one swift move!
Re: Multi-line comments in perl code?
by iankorf (Acolyte) on Jul 14, 2006 at 18:59 UTC
    I think it's a good idea to program in the idiomatic standard of a language. Everyone knows that Perl comments begin with #. Using POD for multi-line comments is a bit of a hack. Sure, it's a little more work to type in several lines of #, but it's the expected way. You won't confuse anyone by doing it.

Log In?
Username:
Password:

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

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

    No recent polls found