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

This works great perl -e '$x = 8; $xr = "x"; $y = ${ $xr }; print "$y\n";' as expected.

Now, nevermind how silly this seems, I have a good reason which isn't worth explaining... How can I get this to work?

perl -Mstrict -e 'no strict "refs"; my $x = 8; my $xr = "x"; my $y = ${ $xr }; print "$y\n";'

Replies are listed 'Best First'.
(jeffa) Re: scalar ref help?
by jeffa (Bishop) on Dec 16, 2002 at 14:56 UTC
    Use package global variables instead of lexical ones:
    perl -Mstrict -le 'no strict "refs";use vars qw($x $xr $y); $x = 8;$xr = "x"; $y = $$xr; print $y;'
    Heh heh ... but why?

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      perl -Mstrict -le 'no strict "refs";use vars qw($x $xr $y); $x = 8;$xr = "x"; $y = $$xr; print $y;'

      This works because you can only use symbolic references where the variables are visible in the package symbol table; lexical ( i.e. my() ) variables are not (as you can confirm with the Perl debugger).

      Camel 3rd Ed. Ch. 8 refers*

      *Sorry

Re: scalar ref help?
by Tanalis (Curate) on Dec 16, 2002 at 15:02 UTC
    You can use eval to evaluate a string, not unlike this:
    use strict; my $x = 8; my $xr = "x"; my $y = eval "\$$xr"; print $y;

    You should see that in the code, eval evaluates the string $x and returns the value of the variable, in this case 8.

    Hope that helps ..
    -- Foxcub

Re: scalar ref help?
by Aristotle (Chancellor) on Dec 16, 2002 at 19:46 UTC

    Just to be sure, I want to advise you to read Dominus' archived newsposts, part one, two and three on Why it's stupid to 'use a variable as a variable name' if you haven't seen any detailed argumentation on the subject yet. There is only very rarely a valid reason to use symbolic references (much less heavy artillery like eval!).

    What you're trying to do can be achieved with a hard reference as well:

    perl -Mstrict -we'my $x = 8; my $xr = \$x; print $$xr, "n";'

    If you already know all this and know that you really need symbolic references, disregard this post (but not without careful reconsideration about whether you really need symrefs :-) ).

    Makeshifts last the longest.