There are several ways. You can play with select() as per chromatic's or plaid's posts. But if you have control over the subroutines you are better off printing directly to the filehandle when that's what you want to do. I also wanted to point out that plaid preserved the old filehandle, but <sigh> he didn't check for success opening the filehandle. Having just run into an issue with this, I'll also suggest localizing the filehandle to the subroutine. So my suggestion:
{ my $i = 1; # Function static var... ooooh. sub Whatever { my $select = (defined $_[0]) ? $_[0] : 0; my $old_fh; local *FH; open FH, ">>$file" or die "Failed to open $file, $!"; if( $select ) { $old_fh = select FH }; print FH "$i This will go to $file\n"; print "$i This will go to $file if \$select($select) is true.\n"; if( $select ) { select $old_fh } close FH or die "Failed to close $file, $!"; $i++; } } Whatever(0); Whatever(1); # Now the second print goes to FH.
I did some extra stuff there to make it more clear. The $i gets incremented with each call so you can differentiate the print outs. My first version of this post had the select before I opened the filehandle. I don't recommend that as any print between the select and the open would bomb. So I fixed my example.

In reply to RE: It's friday, I can't think. by Adam
in thread It's friday, I can't think. by Pearte

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.