There are a number of things in this program that could be improved. The use of -w and use strict is very good, of course.
When checking the result of open() and similar functions, you should print $!, which contains the system error message. You're printing "File does not exist", when the open could have failed for some other reason, such as the wrong permissions on the file.
open(FILE, "file") or die "Cannot open file for reading: $!\n";
In the for loop, you copy $file[$n] to $_ and then print $_, instead of printing $file[$n] directly.
print FILE $file[$n];
But your for loop is written for C, rather than for Perl. This loop should be written with foreach instead. (Making it appropriate to print $_ again.)
foreach (@file) {
print FILE $_;
}
Your three additional print statements can be combined into one print statement (that should print to FILE rather than STDOUT) using a here doc.
print FILE <<EOT;
add whatever here
to end of txt.
EOT
Now the program looks like this:
#!/usr/bin/perl -w
use strict;
open(FILE, "file") or die "Can't open file for reading: $!\n";
my @file = <FILE>;
close(FILE);
open(FILE, ">file") or die "Can't open file for writing: $!\n";
foreach (@file) {
print FILE $_;
}
print <<EOT;
add whatever here
to end of txt.
EOT
close(FILE);
Of course, other improvements could be made, like printing the whole array at once, but I'm keeping in mind your remark that this structure allows you to make minimal changes to the code to edit the lines when you print them back out.
Places to look for more info on the suggestions I made: perlvar for $!; print; perlsyn for foreach loops; perldata for here-docs.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.