有一個有名字的檔案,顯示檔案中的人,然后問這個人是否要注冊,同意 Y,提示他們輸入他們的名字,然后將他們的名字添加到檔案的末尾(如果他們說 y)使用 Perl 將名稱附加到檔案末尾。
這是任務,下面的代碼主要是功能性的。但是,當您輸入名稱時,它會洗掉以前可能已在檔案中的所有其他名稱。
my $file = "name.txt";
# Use the open() function to open the file.
unless(open FILE, $file) {
# Die with error message
# if we can't open it.
die "\nUnable to open $file\n";
}
while(my $line = <FILE>) {
print $line;
}
open (fh, ">", "name.txt");
print "Do you want to sign up? \n";
$choice = <STDIN>;
$y = "yes\n";
if ($choice eq $y) {
print "Enter your name\n";
}
$a = <>;
# Writing to the file
print fh $a;
close(fh) or "Couldn't close the file";
uj5u.com熱心網友回復:
你打開檔案的方式,你打開它寫(>),而不是追加(>>)。
改變
open (fh, ">", "name.txt");
包括>>而不是>:
open (fh, ">>", "name.txt");
此外,Perl Appending 將文本附加到檔案的底部。如果您想附加到檔案的開頭,請查看此答案。
uj5u.com熱心網友回復:
主要問題是您第二次打開檔案時使用了錯誤的模式。從開放:
如果 MODE 是 >,則打開檔案進行輸出,首先截斷現有檔案(“破壞”)并新建不存在的檔案。如果 MODE 是>>,則打開檔案以進行追加,必要時再次創建。
你的檔案被覆寫的原因是你用 來打開它>,這會破壞你現有的檔案。正如檔案所述,您需要使用>>將行附加到檔案的末尾。
另一個問題是,即使用戶輸入no而不是yes,代碼仍然會提示輸入名稱,然后將名稱寫入檔案。除非用戶輸入yes,否則您不想寫入檔案,因此所有代碼都屬于if塊內。
這是撰寫代碼的更傳統的方法:
use warnings;
use strict;
my $file = 'name.txt';
open my $fh, '<', $file or die "\nUnable to open $file: $!\n";
while (my $line = <$fh>) {
print $line;
}
close $fh;
print "Do you want to sign up? \n";
my $choice = <STDIN>;
my $y = "yes\n";
if ($choice eq $y) {
print "Enter your name\n";
my $name = <>;
open $fh, '>>', $file;
print $fh $name;
close $fh;
}
使用strict和很重要warnings。使用詞法檔案句柄 ( $fh) 而不是裸檔案句柄 ( FILE)有很多好處。明確使用模式 for 是一種很好的做法open,即使打開輸入 ( <) 也是如此。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316259.html
標籤:perl
上一篇:從文本檔案中決議字串
