You'll have to forgive me, I didn't see the original code before it was changed. However, the following simple test works fine for me. It even handles the case where you change the value of the handle after use'ing the module. The key, of course, being that you have to explicitly take the reference to the variable in the use line (and never dereference it in the module until you're actually using it).
Test Module:
package MyTst;
use warnings;
use strict;
our $Object;
sub import {
my $class = shift;
$Object = shift;
{
no strict 'refs';
*{caller().'::transaction'} = \&transaction;
}
}
sub transaction(&) {
$$Object->begin();
shift()->();
$$Object->end();
}
1;
Test program:
#!/usr/bin/perl
use warnings;
use strict;
our $tst = TstPkgA->new();
use MyTst \$tst;
transaction {
print "Transaction A!\n";
};
$tst = TstPkgB->new();
transaction {
print "Transaction B!\n";
};
exit;
#*************** Test Classes ***************#
package TstPkgA;
sub new {
return bless {}, 'TstPkgA';
}
sub begin {
print "TstPkgA::begin\n";
}
sub end {
print "TstPkgA::end\n\n";
}
package TstPkgB;
sub new {
return bless {}, 'TstPkgB';
}
sub begin {
print "TstPkgB::begin\n";
}
sub end {
print "TstPkgB::end\n";
}
Output:
TstPkgA::begin
Transaction A!
TstPkgA::end
TstPkgB::begin
Transaction B!
TstPkgB::end
Of course, none of this helps with the case where you want multiple packages to be able to use their own transaction handle. *shrug*
Update: I vote for crenz's way of handling this. You could do it (even the for-style) with source filters. I'm not sure I agree that filters are really a bad way to go with this, as you are adding syntax to the language. *shrug* As long as you handle it with care, you shouldn't necessarily add any parsing bugs. Update2: Heck, you could even steal code from TheDamian's Switch and blame any bugs on him. ;)
bbfu
Black flowers blossom
Fearless on my breath |