You can attach it to either a sub reference, or as a scalar to a sub reference
or*p2::func = $func; package p2; our $x = 100; func();
*p2::func = \$func; package p2; our $x = 100; $func->();
However, both of those will still use the '$x' global defined in package 'p1'. To fix that, rely on parameters instead of a global var.
#!/usr/bin/perl use warnings; use strict; package p1; our $x = 1; my $func = sub { print $_[0],"\n" }; $func->($x); *p2::func = $func; package p2; our $x = 100; func($x);
Or use caller to determine where the function was called from (very messy).
#!/usr/bin/perl use warnings; use strict; package p1; our $x = 1; my $func = sub { my $pkg = (caller)[0]; no strict 'refs'; print ${"${pkg}::x"},"\n" }; $func->(); *p2::func = $func; package p2; our $x = 100; func();
In reply to Re: anonymous sub, packages, global variables
by wind
in thread anonymous sub, packages, global variables
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |