john-jones
john-jones

Reputation: 7780

How can I comment out only part of a line in Perl?

How do I comment a part of a single line in Perl, like the following line:

 if($clevel==0){#never happends}

I would like to be able to comment that last closing bracket, without going to a new line.

Upvotes: 18

Views: 21704

Answers (6)

mosh
mosh

Reputation: 1528

Use a string as an inline comment:

perl -lne '$a++; q#some explanation#;print;'

Inline commenting is necessary for commenting perl code embedded in Makefiles (and Bash script and Vim Scripts) as in this vimscript call perl .. VIM thesaurus file

Upvotes: 6

Michael Horojanski
Michael Horojanski

Reputation: 4711

Part of line or multiply line comment in perl:

=comment
...
...
...

=cut

Upvotes: -1

Joe
Joe

Reputation: 2587

Any reason you can't write :

if($clevel==0){#never happends}

as :

if($clevel==0){} #never happens

There are some tricks you can do to hide messages, such as:

0 and 'some comment'

But you're just going to make it more confusing if someone else has to maintain your code in the future.

Working within the constraints of a language, rather than trying to force it to act like some language you're more familiar with often leads you to learn new things. I personally hate working in IDL, but some of the tricks for dealing with poor loop performance led me to optimize code I've since written in other languages.

Upvotes: 7

mob
mob

Reputation: 118635

If it's really that important, use source filtering.

# C_Style_Comments.pm
package C_Style_Comments;
use Filter::Simple;
FILTER {   s{/\* .* \*/}{}gmx    };
1;

$ perl -MC_Style_Comments -e 'print /* 5, No wait, I mean */ 3'
3

Upvotes: 12

Axeman
Axeman

Reputation: 29854

A # and then a line break. You can treat them as a bracket of sorts, since little in Perl looses its meaning from being on different lines.

my $ans = 2 + rand( 5 ) + $pixels / FUDGE_FACTOR;

To

my $ans = # 2 + 
    rand( 5 ) + $pixels # / FUDGE_FACTOR
    ;

Or from:

if ( dont_know_how_this_breaks() && defined $attribute ) { 
   #...
}

To:

if ( # dont_know_how_this_breaks() && 
     defined $attribute ) { 
   #...
}

Upvotes: 6

lexu
lexu

Reputation: 8849

The # sign starts a comment that ends with the end of the line.

Upvotes: 11

Related Questions