X hits on this document

PDF document

Running and Debugging Perl - page 26 / 30

69 views

0 shares

0 downloads

0 comments

26 / 30

Chapter 9

Have Truthful, Helpful Comments

Comments are a useful memory aid to help you keep track of what's going on in the program, so try and use them as intended. Comments that explain data flow – what the data means and where it comes from

  • are more helpful than comments that explain what you're doing. Contrast the usefulness of these two

sections:

$a = 6.28318; # Assign 6.28318 to $a

$a = 6.28318; # pi*2

The problem with comments is that you have to keep them up to date when you change the code. Make sure your comments aren't a distraction (at best) or (at worst) downright misleading. There's an old saying: 'If code and comments disagree, both are probably wrong.'

Keep the Code Clean

Tidy code is much easier to understand and debug than messy code. It's easier to find problems if, among other things, you make sure to always:

keep parallel items aligned together in columns keep indentation regular keep to one statement per line split long statements over multiple lines use white-space characters to increase readability

Again, contrast these two snippets. There's this:

while (<>)

{

if ( /^From:\s+(.*)/

)

{ $from

= $1 }

if ( /^Subject:\s+(.*)/ )

{ $subject = $1 }

if ( /^Date:\s+(.*)/

)

{ $date

= $1 }

print "Mail from $from on $date concerning $subject\n" unless /\S+/;

next until /^From/;

}

versus this:

while(<>){if(/^From:\s+(.*)/){$from=$1} if(/^Subject:\s+(.*)/){$subject=$1} if(/^Date:\s+(.*)/){$date=$1} print "Mail from $from on $date concerning $subject\n" unless /\S+/; next until /^From/;}

Which one would you rather debug?

304

Document info
Document views69
Page views69
Page last viewedSat Dec 03 17:53:56 UTC 2016
Pages30
Paragraphs723
Words10014

Comments