6

It seems that every time I call spurt without :append, it will open and overwrite the file and then close the file automatically. I have been writing thousands of lines to a file in a routine using spurt. Now it seems like a big waste of I/O resources. I guess if I need to write thousands of lines, I should always use "open" to get a file handle instead. Comments?

JJJ
  • 32,902
  • 20
  • 89
  • 102
lisprogtor
  • 5,677
  • 11
  • 17
  • 1
    Yes use [`open`](https://docs.perl6.org/routine/open) instead. – Håkon Hægland Dec 29 '18 at 07:06
  • 1
    I'm confused. You write that "open ... overwrite ... close ... seems like a big waste of I/O resources." Why? Also, "I guess if I need to write thousands of lines, I should always use "open" to get a file handle instead [of `spurt`]." and @HåkonHægland responds with an upvoted "yes". Again, why? Presumably the same confusion is leading me to both of my "Why?"s and there's just one key thing I'm missing. But I've reread your question a couple times, reread the doc, and I'm still not getting what problem you're seeing let alone how using `open` instead of `spurt` fixes it. TIA for deconfusion. – raiph Dec 29 '18 at 10:53
  • 2
    In the beginning we had 'open...read/write...close'. A frequent use case was reading the whole file, so `slurp` was invented. Writing the whole file at once was useful as well, so `spurt` was added. You can always use the original routines if you don't have the simple use cases. – Curt Tilmes Dec 29 '18 at 12:56

1 Answers1

7

Yes, use open to get a file handle, and use print or say (or write for binary data) to append to it.

spurt is only useful for one-off operations, and meant to relieve you having to write open, print and close for a single logical write operation.

moritz
  • 12,710
  • 1
  • 41
  • 63
  • 2
    Thank you moritz, Hakon Haegland, raiph, and Curt Tilmes for clearing up my question. raiph, I wasn't careful enough in using "open" vs "spurt". Now I understand: with open, the process is: open file, (write a line) xx 1000, close file; with spurt, it is: (open file, write a line, close file) xx 1000. With spurt, there are 1000 open and 1000 close operations. Thanks !!! – lisprogtor Dec 30 '18 at 05:16