++toolic. You forgot explicitly state a couple of pieces of good advice that you followed in your fixed code. Since negzero7 is an admitted newbie, it's worth spelling them out.
- Use the 3 argument version of open.
- Use lexical filehandles.
negzero7, when I am trying to debug a thorny bit of code or learn a new language, I'll sometimes resort to using CS 101 style comments.
#!usr/bin/env perl
open ( # open a filehandle
test, # called 'test'
"@ARGV" # pointing to file specified in arguments
);
while ( # Loop
<test> # read line from filehandle "test" and assign to $_
) {
$_ =~ <test>; #
chomp; # remove newline from end of $_
s/(th)/TH/gi; # Case insensitive replace 'th' with TH everywhere
print "$_\n"; # print $_ with a new line
}
By over-commenting everything I can document my assumptions about every bit of code. Then I can RTFM and verify my understanding is correct. If my first pass does not find the problem, I return and look for anything that I did not comment fully enough.
For example, my notes on the open call were not exhaustive. "@ARGV" stringifies the @ARGV array, by stringifying each element of the array and inserting a space between members of the array: "$ARGV[0] $ARGV[1] $ARGV[2] ... $ARGV[n]".
Sometimes a second pass is not detailed enough. A third pass would show that, the list separator is inserted between elements, which is usually a space, but it can be redefined by setting $". So "@ARGV" is really:
"$ARGV[0]$"$ARGV[1]$"$ARGV[2]$"...$"$ARGV[n]".
I don't leave these kinds of comments in production code--there they'd do more harm than good. But for learning a new language or debugging a tough problem, I find this procedure hard to beat.
|