在perl中从文本文件向textarea写入文本
我正在尝试用文本填充文本区域。 文本将是用户的评论。它将从名为comments.txt的文件中加载 文件模板为:在perl中从文本文件向textarea写入文本,perl,cgi,Perl,Cgi,我正在尝试用文本填充文本区域。 文本将是用户的评论。它将从名为comments.txt的文件中加载 文件模板为: username1 commentscomments commentscomments username2 commentscommentscome comchefhjshfhhfjdjdj dfhfhjdijedhdjdjdjdj username3 februgusyfvretgtyef 我还有一个名为accounts.txt的文件,它存储用户名 我当前的代码
username1
commentscomments
commentscomments
username2
commentscommentscome
comchefhjshfhhfjdjdj
dfhfhjdijedhdjdjdjdj
username3
februgusyfvretgtyef
我还有一个名为accounts.txt的文件,它存储用户名
我当前的代码只是将整个comments.txt文件写入textarea
my $username=(param('username'));
open my $FHIN, '<', "comments.txt" || die "$!";
my @fhin = <$FHIN>;
print textarea(-name=>"CommentArea",-default=>"@fhin",-rows=>10,-columns=>60);
如果username2是已登录的用户
感谢您的帮助 假设您有一个所有用户帐户的列表,并将其放入一个散列中,您可以按如下方式进行操作
sub get_comments {
my ($username, $filename, $all_users) = @_; # $all_users is a hashref
open my $FHIN, '<', $filename or die "Cannot open $filename for reading: $!";
my @comments;
my $found; # starts out as undef
while (my $line = <$FHIN>) {
chomp $line;
if (exists $all_users->{$line}) {
last if $found; # stop once we find another user
if ($line eq $username) {
$found++;
next;
}
}
push @comments, $line if $found;
}
return \@comments;
}
my $comments = get_comments(param('username'), 'comments.txt', $all_users);
print textarea(
-name => "CommentArea",
-default => join("\n", @{ $comments }),
-rows => 10,
-columns => 60,
);
您能否区分文件中的用户名和注释行?很难确定什么时候停止阅读。通常,您可以使用sub来读取文件。您需要检查当前行是否包含用户名。如果是,则开始阅读所有行,直到找到下一个用户名。但是如果没有标记,你怎么知道它是不是用户名呢?我想的是在每一行检查帐户文件。单独的问题是:在
打开时使用或而不是|
,因为你不会像写的那样使用后者捕捉错误,因为它被解析为打开(我的$FHIN,'如果username3
在自己的行中是username1
下的第一条注释,并且username3
被发送到get_comments()
?它将返回username1
s first commentusername3
下的剩余注释。这当然很糟糕。但如果没有用户名分隔符,这是一个设计缺陷,我真的无法解决。另请参阅我对该问题的评论。
sub get_comments {
my ($username, $filename, $all_users) = @_; # $all_users is a hashref
open my $FHIN, '<', $filename or die "Cannot open $filename for reading: $!";
my @comments;
my $found; # starts out as undef
while (my $line = <$FHIN>) {
chomp $line;
if (exists $all_users->{$line}) {
last if $found; # stop once we find another user
if ($line eq $username) {
$found++;
next;
}
}
push @comments, $line if $found;
}
return \@comments;
}
my $comments = get_comments(param('username'), 'comments.txt', $all_users);
print textarea(
-name => "CommentArea",
-default => join("\n", @{ $comments }),
-rows => 10,
-columns => 60,
);
<textarea name="CommentArea" rows="10" cols="60">commentscommentscome
comchefhjshfhhfjdjdj
dfhfhjdijedhdjdjdjdj</textarea>