@@ -333,10 +333,48 @@ to L<Str>.
333
333
334
334
= head2 method close
335
335
336
- Will close a previously opened filehandle.
336
+ Defined as:
337
+
338
+ method close(IO::Handle:D: --> Bool:D)
339
+ multi sub close(IO::Handle $fh)
340
+
341
+ Closes an open file handle. It's not an error to call C < close > on an
342
+ already-closed filehandle. Returns C < True > on success.
343
+
344
+ It's a common idiom to use L « C < LEAVE > phaser|/language/phasers#LEAVE» for
345
+ closing the handles, which ensures the handle is closed regardless of how the
346
+ block is left.
337
347
338
348
= for code :skip-test
339
- $fh.close;
349
+ if $do-stuff-with-the-file {
350
+ my $fh = open "path-to-file";
351
+ LEAVE close $fh;
352
+ # ... do stuff with the file
353
+ }
354
+
355
+ sub do-stuff-with-the-file (IO $path-to-file)
356
+ my $fh = $path-to-file.open;
357
+
358
+ # stick a `try` on it, since this will get run even when the sub is
359
+ # called with wrong arguments, in which case the `$fh` will be an `Any`
360
+ LEAVE try close $fh;
361
+
362
+ # ... do stuff with the file
363
+ }
364
+
365
+ with "foo/bar".IO.open(:w) {
366
+ .spurt: "I ♥ Perl 6!";
367
+ .close;
368
+ }
369
+
370
+ B < Note: > unlike some other languages, Perl 6 does not use reference counting,
371
+ and so B < the file handles are NOT closed when they go out of scope > . They
372
+ I < will > get closed when garbage collected, however an explicit C < close > is
373
+ recommended, so that your program does not open too many files at the same time,
374
+ triggering exceptions on further opens.
375
+
376
+ As a simpler alternative, the L < IO::Path > type provides many methods that let
377
+ you work with files without dealing with file handles directly.
340
378
341
379
= head2 method flush
342
380
0 commit comments