I'm writing a module that uses File::Rsync, which has an option to capture the output from rsync through subrefs. From the docs:
The outfun and errfun options take a function reference. The function is called once for each line of output from the rsync program with the output line passed in as the first argument, the second arg is either 'out' or 'err' depending on the source. This makes it possible to use the same function for both and still determine where the output came from.

This is fine if you want to write the output to a log file or some such thing, but if you want to capture the output into a variable, you pretty much have to make it global. Something like:

package MyModule; use File::Rsync; my %rsync_out; my $rsync=File::Rsync->new( { outfun => &rsync_out, errfun => &rsync_out, } ); ... sub rsync_out { my ($message, $type)=shift; $rsync_out{$type}.="$message\n"; }

That should work, but it uses a global variable that is set somewhere downstream in the script in a subroutine, so it is somewhat ugly.

I have a sneaky feeling that something can be done here with references and closures, but I'm drawing a blank as to what exactly.

So, what's the monks' opinion: is this a tolerable use of a global variable or should I try to be clever and avoid the global (suggestions as to what exactly 'clever' means in this case are welcome :) )? Personally, I'm inclined to go with the global var, for the sake of simplicity and maintainability.

CU
Robartes-


In reply to File::Rsync output functions and global variables by robartes

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.