Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Can I write and close a file in a subroutine?

by Anonymous Monk
on Nov 15, 2012 at 07:26 UTC ( #1003947=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I have a question regarding subroutine. If I opened a file(not closed now) and doing some writings and these is a case to go to a subroutine and check. So I want to check for that case and if it is positive need to write something also to the file and there itself need to close, without exiting from the subroutine. Is it possible, or I need to go out of the subroutine to do that..?

Comment on Can I write and close a file in a subroutine?
Re: Can I write and close a file in a subroutine?
by davido (Archbishop) on Nov 15, 2012 at 07:36 UTC

    Are you trying to do something like this?

    open my $fh, '>', 'outfile.txt'; test_and_write( $fh ); sub test_and_write { my $handle = shift; if( rand() > .5 ) { close $handle; return; } else { print $handle "Still open.\n" return 1; } }

    It's possible. Maybe not a great separation of concerns, but possible.

    If that's not what you're asking, read your question back to yourself and see if it makes sense to you, because it's a little opaque to me.


    Dave

Re: Can I write and close a file in a subroutine?
by choroba (Abbot) on Nov 15, 2012 at 08:18 UTC
    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: perlquestion [id://1003947]
Approved by rovf
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (14)
As of 2014-08-20 20:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (124 votes), past polls