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

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?

Replies are listed 'Best First'.
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.


Re: Can I write and close a file in a subroutine?
by choroba (Bishop) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1003947]
Approved by rovf
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (10)
As of 2018-06-25 12:41 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.