我得到以下代码来尝试打开和写入文件(不加急):
sub MAIN {
my $h = open 'somefile.txt', :w, :a;
for 1..4 {
$fh.put: "hello";
}
$fh.close;
}
我期望的是,每次运行时,都应在文件中附加4行“hello”。但是,它似乎仍然会覆盖文件,在运行2次或更多次之后,仍然只有4行。
$ perl6 opening.p6
$ cat somefile.txt
hello
hello
hello
hello
$ perl6 opening.p6
$ cat somefile.txt
hello
hello
hello
hello
添加或删除
:a
或:append
似乎并不影响此行为,我缺少什么?
最佳答案
根据open documentation,您要
my $h = open 'somefile.txt', :a;
一字母和两字母的简写不是修饰符,但可以单独使用,
:w
扩展为:mode<wo>, :create, :truncate
和
:a
扩展到:mode<wo>, :create, :append
模仿POSIX。
实际上,您尝试的
:w, :append
组合也应该以附加模式打开文件-但仅在先将其截断之后才可以打开文件,这似乎并不是特别有用...
关于string - 为什么用:w and :append still overwrite the file?打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56302171/