Looking for some ideas / advice...
I have a method that offers a callback feature. The running context has a variable $meta declared lexically using my. I would like to make that variable available to the callback function somehow. I have considered the following options:
Don't use my; use our, and then local to set the running context. This solution requires the calling context to know about the variable, which means it fails
"use strict" (see example code below). Declaring the variable in the calling context would pass "use strict", but due to the way closures work, the local value would not be available in the running context, so this doesn't work.
Pass the variable as an argument to the callback. This solution is inconvenient because it so happens that the number of arguments to the callback vary. HTML::Parser has a solution to this where the caller sets the arguments it wants to be passed.
Make the variable available to the callback as a package global. This is the solution used by File::Find for example, which requires the variable to be global (though it can be set local in the running context), yields long variable names ($File::Find::dir, etc), and gets more complex when inheritance is involved.
Use a "special" variable. This solution works nicely. I'm not aware of any way to declare a variable $meta as being "special" however, so a different name must be used, such as: local ${^_meta} = 1;
I also tried eval (see below), but this didn't work (I didn't really expect it to, but worth a shot).
All these solutions seem ugly to me, but just wondering if anyone has other ideas or sees any reason to prefer one method over the other...
#!/usr/bin/perl
#use strict;
package pkg1;
sub test1
{
my $meta = 1;
$_[0]->(1);
eval { $_[0]->(2) };
eval '$_[0]->(3)';
}
package pkg2;
{
pkg1::test1 ( sub { print "$_[0]: meta=$meta;\n"; } );
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.