Monks,

I ran across a strange bug in the code of one of my modules, and I'm puzzled.

I use the $haveModule = eval { require Module; 1; } idiom fairly frequently, but it broke down for the Capture::Tiny module. Basically, it boils down to Capture::Tiny seemingly requiring module load via a BEGIN block in order to function without error. But I don't understand why, and it chafes me.

Here's code using Capture::Tiny that works:

use strict; use warnings; BEGIN { require Capture::Tiny; } my $out = Capture::Tiny::capture { print "STDOUT output to capture"; } +; print "Captured STDOUT: [" . ( defined $out ? $out : 'undef' ) ."]\n";
Output:
Captured STDOUT: [STDOUT output to capture]

By just removing the BEGIN block around require Capture::Tiny, the code now fails:

use strict; use warnings; require Capture::Tiny; my $out = Capture::Tiny::capture { print "STDOUT output to capture"; } +; print "Captured STDOUT: [" . ( defined $out ? $out : 'undef' ) ."]\n";
Output:
Can't call method "Capture::Tiny::capture" without a package or object + reference at C:\@local\@projects\@tests\test-Capture-Tiny.pl line 5.

The source for Capture::Tiny (@ http://cpan.uwinnipeg.ca/htdocs/Capture-Tiny/Capture/Tiny.pm.html) seems reasonably straight-forward, but I must be missing something.

Can someone offer an explanation for this behavior?

Thanks, in advance, for the illumination.


In reply to Why does Capture::Tiny require loading via BEGIN to successfully function? by Wyrdweaver

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.