尝试在新行上将新用户追加到文本文件中,但我的所有行都会被修改。
这是我的文字档案:
Joe W,john,asdf
Arnold K,bnads,1234
Marissa G,mglav,传递
#!/usr/bin/perl
open(FILE, "+<test.txt") or die "Couldn't open file $!";
if ($user eq $fields[1]) {
print "Taken";
elsif ($user ne $fields[1]) {
print FILE "$user";
}
}
close(FILE);
当我运行此文件时,我的文本文件变为
Joe W,john,asdf
测试K,bnads,1234
测试G,mglav,传递
测试
答案 0 :(得分:0)
将用户添加到文件末尾,仅在尚未使用时
my $taken = 0;
while (my $line = <FILE>) {
chomp $line;
# splits each line into three fields
my @fields = split "," , $line;
if ($user eq $fields[1]) {
print "Username is taken.\n";
$taken = 1;
last;
}
}
if (!$taken) {
print FILE "$user\n";
}