in reply to Can I write and close a file in a subroutine?
If you use lexical filehandles, you can pass them directly:sub test_and_write { my ($TWR, $condition) = @_; print $TWR "True\n" if $condition; }
Closing the file in the subroutine is dangerous, though. You would not be able to print anymore to the filehandle, but this fact would not be obvious from the place where the routine would be called (action at a distance). Better rethink the logic (e.g., the subroutine can return a boolean value, if it is true, close the file after calling it).open my $OUT, '>', 'output.txt' or die "Cannot open output.txt: $!"; test_and_write($OUT, int rand 2);
|
|---|