I got the following code to try out file opening and writing (without spurt):
sub MAIN {
my $h = open 'somefile.txt', :w, :a;
for 1..4 {
$fh.put: "hello";
}
$fh.close;
}
What I expected is that with each run, it should append 4 additional lines with "hello" to the file. However it still seems to overwrite the file, after 2 or more runs there are still only 4 lines.
$ perl6 opening.p6
$ cat somefile.txt
hello
hello
hello
hello
$ perl6 opening.p6
$ cat somefile.txt
hello
hello
hello
hello
Adding or removing :a
or :append
doesn't seem to influence this behaviour, what am I missing?
w : Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist.
When you open a file in append mode, the seek pointer points to the end of the file (the pointer position will be non-zero if the file is not empty). On new (empty) files, the end is equal to the beginning. So appending is the same as overwriting. So basically you are saying that there would not be any difference.
Filename is the name of the file with which we will be working on. Mode means the method in which we want to open a file & there are 4 basic modes. “r” for reading. “w” for writing. “a” for appending.
According to the open documentation, you want
my $h = open 'somefile.txt', :a;
The one and two-letter shorthands are not modifiers, but useable in isolation, with :w
expanding to
:mode<wo>, :create, :truncate
and :a
expanding to
:mode<wo>, :create, :append
mimicking POSIX.
The combination :w, :append
you tried should in fact also open the file in append mode - but only after truncating it first, which doesn't seem particularly useful...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With