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

I want an anonymous scalar to which i can refer to from an unknown number of other scalars. The only thing I can come up with (I'm not that familiar with PERL, yet) is this (example code):
$variable = "something"; $variableRef1 = \[ $variable ]->[ 0 ];
This makes it possible to change $variable without changing $$variableRef1 which is what I want. I want to use this in a loop where i give $variable different values but want a copy of each value, but only 1 copy and an unknown number of references to this one copy. How can I do this without constructing an anonymous array (or hash) and consume minimal time and memory?

Then later, if I change (in this example) $variableRef1 to refer to something else ($variable is also changed, so the refcount should be 0), PERL's garbage collection will free the now unused memory, right?

--
Alex

Replies are listed 'Best First'.
Re: How can I create an anonymous scalar?
by suaveant (Parson) on Jul 26, 2001 at 17:57 UTC
    $sref = \"Hello World";
    or
    $sref = \( ...something yielding a scalar value...);

    should give you an anonymous scalar ref

    $variableRef1 = \[ $variable ]->[ 0 ];
    is just ugly... :)

                    - Ant

Re: How can I create an anonymous scalar?
by merlyn (Sage) on Jul 26, 2001 at 18:31 UTC
Re: How can I create an anonymous scalar?
by PrakashK (Pilgrim) on Jul 26, 2001 at 18:19 UTC
    I am confused. Do you really want an anonymous scalar?

    You want to have several references to a scalar and also to be able to change the value of the scalar independently (not via the references). If so, you need to name that scalar with a scalar variable and it won't be anonymous.

    Anyway, what's wrong with a straight reference to a scalar?

    $v = "something"; $ref1 = \$v; $ref2 = \$v; # both $ref1 and $ref2 point to the same variable. # change the value $v = "something else"; # both $ref1 and $ref2 will point to the change +d value $v2 = "new value"; $ref1 = \v2; # $ref2 now points to a new variable # $ref2 will continue to point to $v
    Have I totally misunderstood your question?
      Well, just a bit. I didn't want to change $$ref1 (and $$ref2) if I changed $v. The answer from Randal Schwartz (merlyn) is what I was looking for. Thanks anyway!

      --
      Alex