Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Can I write and close a file in a subroutine?

by choroba (Chancellor)
on Nov 15, 2012 at 08:18 UTC ( #1003954=note: print w/replies, xml ) Need Help??


in reply to Can I write and close a file in a subroutine?

Yes. You can use a filehandle as an argument of a subroutine:
sub test_and_write { my ($TWR, $condition) = @_; print $TWR "True\n" if $condition; }
If you use lexical filehandles, you can pass them directly:
open my $OUT, '>', 'output.txt' or die "Cannot open output.txt: $!"; test_and_write($OUT, int rand 2);
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).
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1003954]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2016-12-09 12:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (150 votes). Check out past polls.