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

#!/usr/bin/perl $var = "World"; ${$var} = "hello"; print "Variable : $var \n"; print "Interpolated var : ${$var} \n";
This program executes perfect.
#!/usr/bin/perl use strict; my $var = "World"; my ${$var} = "hello"; #gives syntax error print "Variable : $var \n"; print "Interpolated var : ${$var} \n";
cheers Rock

Replies are listed 'Best First'.
Re: String interpolation problem
by davido (Cardinal) on May 03, 2004 at 07:18 UTC
    The problem really has nothing to do with string interpolation as your node title asserts. It actually should be giving you the following error.

    Can't declare scalar dereference in my at mytest.pl line 7, near "} =" Execution of mytest.pl aborted due to compilation errors.

    The error is because you're trying to declare a lexical variable with 'my' that is a dereferenced symbolic reference. That just doesn't make sense.

    What all that means is that you cannot use a symbolic reference as the name of a lexically declared variable. The fact is that lexical variables can't be referred to symbolically. All symbolic refs refer to package globals.

    See perlref for details. Also take note that in 99.9% of the common-code situations, you don't really need to be thinking in terms of symbolic references anyway. You can almost always accomplish what your objective is more cleanly with a lexical. If you're interested in "variable names", try using a hash instead, where the keys are represented by those names instead of mucking around in the global symbol table. The global symbol table is, after all, just a glorified hash.


    Dave

Re: String interpolation problem
by Zaxo (Archbishop) on May 03, 2004 at 07:25 UTC

    This isn't really interpolation. You are initializing $World with a soft reference to it. strict objects to that. Even without strict, you get a syntax error if you try to declare $World as aq lexical that way. It reads,

    $ perl -e'my $var = "World";my ${$var} = "hello";' Can't declare scalar dereference in my at -e line 1, near "} =" Execution of -e aborted due to compilation errors. $ perl -e'my $var = "World";${$var} = "hello";print $World' hello$

    After Compline,
    Zaxo