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

Is it possible to pass on tied vars by reference ? I would think the following code works, but it doesn't :(
use strict; use Tie::Hash::Stack; my (%a, %b); tie %a, 'Tie::Hash::Stack'; print( (tied(%a) ? 'tied' : 'NOT tied'), " a\n"); *b = \%a; print( (tied(%b) ? 'tied' : 'NOT tied'), " b\n");

--
Jaap Karssenberg || Pardus (Larus)? <pardus@cpan.org>
>>>> Zoidberg: So many memories, so many strange fluids gushing out of patients' bodies.... <<<<

Replies are listed 'Best First'.
Re: How do I pass refs to tied vars ?
by broquaint (Abbot) on May 19, 2003 at 15:15 UTC
    Globs are not lexical (unless diotalevi is involved ;) e.g
    use strict; use Tie::Hash; my(%a, %b); tie %a, 'Tie::StdHash'; print( (tied(%a) ? 'tied' : 'NOT tied'), " my %a\n"); *b = \%a; print( (tied(%main::b) ? 'tied' : 'NOT tied'), " %main::b\n"); print( (tied(%b) ? 'tied' : 'NOT tied'), " my %b\n"); __output__ tied my %a tied %main::b NOT tied my %b
    As you can see your problem is that you're testing the lexical %b and not the package %b.
    HTH

    _________
    broquaint

Re: How do I pass refs to tied vars ?
by japhy (Canon) on May 19, 2003 at 15:36 UTC
    Oooh! Use Lexical::Alias!
    use Tie::Hash::Stack; use Lexical::Alias; tie my(%a), 'Tie::Hash::Stack'; alias %a => my(%b);
    That's if you're using Perl 5.8+. If you're below that, do:
    use Tie::Hash::Stack; use Lexical::Alias 'alias_h'; tie my(%a), 'Tie::Hash::Stack'; alias_h %a => my(%b);
    Shameless plug.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: How do I pass refs to tied vars ?
by Zed_Lopez (Chaplain) on May 19, 2003 at 18:00 UTC
    Or there's always, in fact, using an actual reference.
    $b = \%a; print( (tied(%$b) ? 'tied' : 'NOT tied'), " b\n");
    This produces the expected results.
Re: How do I pass refs to tied vars ?
by gmpassos (Priest) on May 19, 2003 at 19:40 UTC
    As everyone said, GLOB aren't lexical.

    In your code, you make tied(%b), where %b isn't %main::b, it's my (%b).

    So, to fix your code, just change:

    ## From: my(%a, %b); ## To: my %a ; use vars qw(%b) ;
    And now you can see the output:
    tied a tied b
    If you want to work with the reference to the tied HASH, use:
    my $b = \%a; tied(%$b) ;
    Or use Lexical::Alias, as japhy said. :-P

    Graciliano M. P.
    "The creativity is the expression of the liberty".