Tue 5 Sep 2006
This may seem trivial, but I believe how we organize programs is directly influenced by how we think. Perhaps learning to better organize code will lead to better organized, more efficient thinking.
-
#!/usr/local/bin/perl -w
-
use strict;
-
my $w_param="-w ";
-
my $tick="'";
-
my $b_param="barcode=";
-
my $or_string=" or ";
-
-
# $a[$i]=$_;
-
# $i++;
-
# print map {$_, "\n"} @a;
-
-
while (@a) {
-
my @output = ();
-
for ( 1..4 ) {
-
last unless @a;
-
}
-
}
-
print $tick;
The author uses an 8 space indent. Here is the same code without the comments with a 4 space indent. I changed the indent to match my own settings. YMMV.
-
#!/usr/local/bin/perl -w
-
use strict;
-
my $w_param="-w ";
-
my $tick="'";
-
my $b_param="barcode=";
-
my $or_string=" or ";
-
-
while (@a) {
-
my @output = ();
-
for ( 1..4 ) {
-
last unless @a;
-
}
-
}
-
print $tick;
Let's look at the code in sections. I'll use comments first.
-
# open file
-
-
# declare some variables
-
my $w_param="-w ";
-
my $tick="'";
-
my $b_param="barcode=";
-
my $or_string=" or ";
-
-
# slurp file into array
-
-
# print two variables (unchanged
-
# since decalaration above)
-
-
# loop through @a
-
while (@a) {
-
-
# create 4 column row for report
-
my @output = ();
-
for ( 1..4 ) {
-
last unless @a;
-
}
-
-
# print this row
-
}
-
-
# print $tick
-
print $tick;
-
-
# exit program and implicitly close file
-
-
__END__
And now the comments only.
-
1. Open file
-
-
2. Declare some variables
-
a. $w_param,
-
b. $tick,
-
c. $b_param, and
-
d. $or_string.
-
-
3. Slurp file into array - @a
-
-
4. Print $w_param and $tick
-
-
5. Loop through @a
-
-
a. Create 4 column row
-
b. Print row
-
c. Contune loop
-
-
6. Print $tick
-
Question: Why open the file (step 1), then slurp it in at step 3 and close is at step 7?
It might make more sense to open, read it, and close it in 3 consecutive steps.
-
1. Open file.
-
3. Slurp file into array - @a
-
3. Close file.
-
-
4. Declare some variables
-
a. $w_param,
-
b. $tick,
-
c. $b_param, and
-
d. $or_string.
-
-
5. Print $w_param and $tick
-
-
6. Loop through @a
-
-
a. Create 4 column row
-
b. Print row
-
c. Contune loop
-
-
7. Print $tick
Now we'll put the code back in.
-
-
# slurp file into array
-
-
# close file
-
close FH;
-
-
# declare some variables
-
my $w_param="-w ";
-
my $tick="'";
-
my $b_param="barcode=";
-
my $or_string=" or ";
-
-
-
# loop through @a
-
while (@a) {
-
-
# create 4 column row for report
-
my @output = ();
-
for ( 1..4 ) {
-
last unless @a;
-
}
-
-
# print this row
-
}
-
-
# print $tick
-
print $tick;
'open' might be better written following a standard format.
Declarations look better when lined up.
-
my $w_param = '-w ';
-
my $tick = "'";
-
my $b_param = 'barcode=';
-
my $or_string = ' or ';
White space should be used to aid readability.
Leave a Reply
You must be logged in to post a comment.