skerr1 has asked for the wisdom of the Perl Monks concerning the following question:

I have two packages: foo and bar. foo "requires" bar, but bar wants to know what foo has set for $value. bar knows foo's name via the caller function. I can't get the syntax right here to access $foo::value. Here is what I have:
package bar; my ($callingPkg) = caller; my $value = something here to reference the calling package's $value;
Can someone help with this? I'd be very grateful.

Thanks,
Shannon

Replies are listed 'Best First'.
Re: reference symbol in calling package namespace
by ikegami (Patriarch) on Dec 05, 2006 at 18:25 UTC

    Alarms bells are ringing. Giant red flags are waving. There's surely a better way of doing what you are trying to do, but you haven't provided us with enough information to help you there. On the off chance that this isn't one of those cases, I'll answer your question. I pity your users and maintainers if you use it.

    my $value_ref = do { no strict 'refs'; \${caller().'::value'} }; print $$value_ref, "\n";

    It will only work if the variable is a package variable (our) as opposed to a lexical variable (my).

    Update: Oops, I had \* instead of \$. Fixed. Tested.

      This is a contained system and this will save more headaches than create. Simply put, we want to access information in once place that the calling namespace has. With Perl there are always better ways to do things. I don't think it is wrong however to access, in a contained system, information that you know will be there. The section is carefully commented and the code is pretty clear (at least it is now with your assistance):
      my ($pkg) = caller; my $value1 = ${$pkg . "::value1"}; my $value2 = ${$pkg . "::value2"};
      I thank you for your help. This resolves my issue.
      Shannon Kerr
Re: reference symbol in calling package namespace
by chromatic (Archbishop) on Dec 05, 2006 at 20:52 UTC
    my $caller = caller(); my $caller_value = $caller->get_value();

    I realize that's not nearly as exciting as using symbolic references, but abstraction avoids a lot of problems.

Re: reference symbol in calling package namespace
by philcrow (Priest) on Dec 05, 2006 at 18:56 UTC
    I second [id://ikegami]'s comments. If anyone outside you module needs to look at or set the value, you should provide methods or functions for them to use. This simplifies not only your immediate problem, but opens an actual API for clever things in the future.

    If you had the methods, knowing the name of the module and the name of the method (even if they are in variables) is far preferable to the games needed to make direct access work.

    Further (added later), you should probably implement an import method in the bar class. It will receive the caller's name, making it even easier to do whatever it is you are doing.

    Phil

    Update: Added the part about import.