Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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

by choroba (Abbot)
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).
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ


Comment on Re: Can I write and close a file in a subroutine?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1003954]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2014-07-31 03:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (244 votes), past polls