I recommend not printing an array like you do. Instead,
i would opt for a scalar. One way to get a scalar from
a file handle (instead of an array) is to join the
array on an empty string.
Also, use CGI!!!! Try this instead:
use CGI qw(:standard);
my $file = 'foo.txt';
my $lines = read_file($file);
print header(), start_form(),
textarea(
-name => 'head',
-value => $lines,
-rows => 6,
-cols => 60,
-wrap => 'soft',
-override => 1,
), p(submit());
my $head = strip(param('head'));
print end_form();
if ($head) {
write_file($file,$head);
}
sub read_file {
my $file = shift;
open(FILE,$file) or die "$file not readable: $!";
my @lines = <FILE>;
close(FILE);
return join('',@lines);
}
sub write_file {
my ($file,$new_head) = @_;
print STDERR "adding $new_head";
open (FILE,'>',$file) or die "$file not writeable";
flock (FILE, 2) or die "$file not lockable";
print FILE $new_head;
close(FILE);
}
sub strip {
my $param = shift;
return '' unless $param;
$param =~ s/^\s+//g;
$param =~ s/\s+$//g;
return $param;
}
The CGI module is used to handle generating the HTML
form and parsing the query string parameters. All
subroutines that you see that are not defined in
this script are defined in CGI.pm - you can read more
about CGI.pm here.
Of interest is the strip() function which does some
basic validation on the text to be written to the file.
In this case, if nothing but whitespace or nothing at all is submitted then the file will not be written to.
The read_file subroutine uses the join trick i mentioned
earlier. This is just one way to convert an array into
a scalar explicitly.
Hope this helps.
P.S. Oh! I really should mention something about the
-override option to the textarea() method. CGI.pm by
default will use the value that was submitted. Be sure that
you specify -override in this situation because you are
wanted to show the contents of the file, not what was
submitted. Comment that line out and see what i mean.
Also, don't forget to properly set file and directory
permissions/ownerships.
jeffa
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
F--F--F--F--F--F--F--F--
(the triplet paradiddle)
|