我该如何使用 Perl 用数组覆盖文件?
我的文件如下所示:
username1
comment
comment
comment
username2
comment
comment
username3
comment
comment
comment
...
Run Code Online (Sandbox Code Playgroud)
我所做的就是首先将这些行加载到数组中。然后遍历数组,将行添加到新数组中。当它找到用户的行时,我想向其添加注释,将触发一个标志,使其在循环的下一个增量中添加注释。然后它只是将其余的行添加到数组中。我想要做的就是使用新数组来覆盖文件。这就是我被困住的地方。
sub AddComment() {
my $username = shift; # the username to find
my $comment = shift; # the comment to add
chomp($comment);
chomp($username);
open my $COMMENTS, '<', "comments.txt" or die "$!"; #open the comments file
my @lines = <$COMMENTS>; #Make an array of the files lines
my @NewCommentsFile; # make an array to store new file lines
my $addCommentNow = 0; # flag to know when to add comment
for my $line (@lines) {
if ($line eq $username) { # if this line is the username
$addCommentNow = 1; # set flag that next line you add comment
push(@NewCommentsFile, $line); # add this line to new array
}
elsif ($addCommentNow eq 1) { # if the flag is 1 then do this
push(@NewCommentsFile, $comment); # add the comment to the array
$addCommentNow = 0; # reset flag
}
else {
push(@NewCommentsFile, $line); #add line to array
}
}
open my $fh, '>', "comments.txt" or die "Cannot open output.txt: $!";
# Loop over the array
foreach (@NewCommentsFile) {
print $fh "$_"; # Print each entry in our new array to the file
}
close $fh;
}
Run Code Online (Sandbox Code Playgroud)
chomp $username但你不是$line,所以$username永远不会平等$line。
您chomp添加了要添加的新注释,但在最后一个循环中您打印时没有换行符。因此,您打印的任何新注释都将被添加到其后面的任何行之前。
您elsif ($addCommentNow eq 1) {将根据输入丢弃当前缓冲区或执行其他奇怪的操作。
尝试这个修改后的代码(仅解决这三个问题):
for my $line (@lines) {
chomp $line;
push(@NewCommentsFile, $line);
push(@NewCommentsFile, $comment) if $line eq $username;
}
open my $fh, '>', "comments.txt" or die "Cannot open output.txt: $!";
foreach (@NewCommentsFile) {
print $fh "$_\n"; # Print each entry in our new array to the file
}
close($fh);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9251 次 |
| 最近记录: |