Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: can't use string as a SCALAR ref while strict refs

by Sweeper (Pilgrim)
on Feb 28, 2002 at 06:38 UTC ( [id://148148]=note: print w/replies, xml ) Need Help??


in reply to can't use string as a SCALAR ref while strict refs

Just use a hard reference:
use strict;
my $b = '1';
my $a = \$b;

$$a = '2';

print $b;
You must declare $b before referencing it as \$b (I know, I have tested my code), because typing
my $a = \$b;
my $b = '1';
in this order will autovivify a variable $main::b and then declare a different $b "my" variable.

The reason why your program prints '1' is nearly the same. You can use symbolic references (opr string references as you call it), only to package variables. You cannot use a symbolic reference to a "my" variable. So, in your code, you have two variables:

my $b
$main::b
That's all !
  • Comment on Re: can't use string as a SCALAR ref while strict refs

Replies are listed 'Best First'.
Re: Re: can't use string as a SCALAR ref while strict refs
by dws (Chancellor) on Feb 28, 2002 at 07:00 UTC
    Another way to look at this is to ponder
    { my $b = '1'; my $a = 'b'; $$a = 2; print "b = $b\n"; } print "b = $b\n";
    and consider which $b is getting set, and why. This might require a detour into the documentation on what, exactly, 'my' does.

      Symbolic references, which the initial question is about, require entries in the symbol table. "my" does not place entries in the symbol table. This explains the behavior the initial poster asked about, and also answers why you will get
      b = 1 b = 2
      for your output. The setting of $$a to 2 sets the global $b to 2, but inside the block $b refers to the lexical $b with no symbol table entry.
      Hope this helps...
      Other posters have mentioned that what the original poster may really want to use are the hard references...

      -JAS

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://148148]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-19 18:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found