How do you append to a file in Perl 6?

  • A+
Category:Languages

I was trying this and a few other things but it truncates the file each time:

my $file = 'primes.txt'; sub MAIN ( Int:D $low, Int:D $high where * >= $low ) {     unless my $fh = open $file, :w, :append {         die "Could not open '$file': {$fh.exception}";     }      for $low .. $high {         $fh.put: $_ if .is-prime;     } } 

Changing this to open $file, :a also seems to truncate the file. This is 2018.04 on macOS.

 


Perl6 &open semantics are based on POSIX, with the following mapping:

:mode<ro>  --> O_RDONLY :mode<wo>  --> O_WRONLY :mode<rw>  --> O_RDWR :create    --> O_CREAT :append    --> O_APPEND :truncate  --> O_TRUNC :exclusive --> O_EXCL 

For convenience, the following shortcuts are provided:

:r      --> :mode<ro> :w      --> :mode<wo>, :create, :truncate :x      --> :mode<wo>, :create, :exclusive :a      --> :mode<wo>, :create, :append :update --> :mode<rw> :rw     --> :mode<rw>, :create :rx     --> :mode<rw>, :create, :exclusive :ra     --> :mode<rw>, :create, :append 

Not all platforms supported by Rakudo (eg Windows, JVM, not even POSIX itself) support all possible combinations of modes and flags, so only the combinations above are guaranteed to behave as expected (or are at least supposed to behave that way).

Long story short, a simple :a absolutely should do what you want it to do, and it does so on my Windows box. If it really truncates on MacOS, I'd consider that a bug.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: