http://www.perlmonks.org?node_id=1003947

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