This works:

sub transform { my ($data,$log_fh) = @_; # Localize the log filehandle so all subroutines can see it local *LOG_FH = $log_fh; ... foo($bar); } sub foo { my ($bar) = @_; print LOG_FH "Processing $bar.\n"; ... }

This doesn't:

sub transform { my $data = shift; local $log_fh = shift; ... foo($bar); } sub foo { my ($bar) = @_; print $log_fh "Processing $bar.\n"; ... }

The parent function transform exists in a separate file which is being required by a file that initializes the log filehandle.

Clearly the second case (localizing an indirect filehandle) forces a compile-time error since $log_fh is not a global. Is there a way to do this with an indirect filehandle or is the first method the "best-practice" way to do it? Why would you ever do it as in the perlfaq (open local $fh...)? Am I wrong for trying?

Thanks.

Update: So I should have realized creating a global filehandle at the top of the second case would fix this problem:

our $log_fh; sub transform { my $data = shift; print $log_fh "Processing data $data.\n"; foo("bar"); } sub foo { my ($bar) = @_; print $log_fh "Processing $bar.\n"; } sub main { open ( local $log_fh, '>', 'test.txt' ) or die "Couldn't open log +file\n"; transform( "data", $log_fh ); } main();

If anybody still cares to add to my understanding I'm always grateful.


In reply to Localizing an indirect filehandle by whakka

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.