Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

strange problem

Status
Not open for further replies.

zfang

Programmer
Apr 3, 2002
23
US
Hi,

I have a strange problem with following code.

code1:

#!/usr/local/bin/perl
my $temp;
my $str;
$str = 'test';
$temp = 'str';
print ${$temp}."\n";

Only a blank line was printed, however if I got ride of the declaration of $str, ie
code 2:

#!/usr/local/bin/perl
my $temp;
$str = 'test';
$temp = 'str';
print ${$temp}."\n";

The output is: test
That's what I wanted, but I don't know why code 1 doesn't work?

Thanks,

George
 
It doesn't work because lexical variables (those declared with my()) don't exist in the symbol table, only package variables do. Therefore, lexical variables are not visible to soft references.
In your example ${$temp} evaluates to ${'str'} so Perl looks for $main::str in the symbol table. If you declared $str with my() it won't exist there so ${'str'} returns undef and you print out just the newline.
(Running the script with warnings on will tell you that you are printing an undefined value.)

See the perlref perldoc for more in depth discussion of this.

jaa
 
jaa, thank you very much for your reply. One more point I want to ask. If I use strict in a code, then I have to declare a variable using my(). So, in this case, are there any ways to get the results as did in code 2?

Thanks,

George
 
Declaring the variable with our() instead of my() writes it into the symbol table but strict will still not allow the soft reference.

One way around this is to locally turn of strict, or even just strict 'refs':
Code:
#!/usr/local/bin/perl
use strict;
my $temp;
$str = 'test';
$temp = 'str';
{
    no strict 'refs';
    print "${$temp}\n";
}  # Enclosing block limits scope of 'no strict'
Usually there are better ways to do something than using soft refs, though.

jaa
 
Thanks a lot. Have a nice weekend.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top