Make a variable reference its own string content

I wanted to make the variable reference my own content, so I did this:

$x=\$x;

but this does not work, as I expected, it has $xbecome a reference to itself, therefore it $$xcoincides with $x. I expected to $$xbe the starting line. Why is this and how should I write correctly without making a copy of the string in $x? Because in some cases it $xcan be a huge string.

+4
source share
2 answers

What you ask is impossible. A variable cannot contain a link and a string. You must use two variables. This leaves you with two options.

Save link in new variable

$ perl -e'
   use feature qw( say );
   my $x = "abc";
   my $y = \$x;
   say $y;
   say $$y;
'
SCALAR(0x232a398)
abc

, , .

, $x . , , .

, var , . , .

$ perl -e'
   use feature qw( say );
   my $x = "abc";
   my $x = \$x;
   say $x;
   say $$x;
'
SCALAR(0x232a398)
abc

$ perl -e'
   use feature qw( say );
   my $x = "abc";
   $x = \( my $container = $x );
   say $x;
   say $$x;
'
SCALAR(0x175cbe0)
abc

. 5.20. 5.20 . , 5.20+; . , (0x2ac53d0) :

$ perl -MDevel::Peek -e'my $x = "abc"; my $y = $x; Dump($_) for $x, $y;' 2>&1 \
   | grep -P '^(?:SV|  FLAGS|  PV)\b'
SV = PV(0x2a9f0c0) at 0x2abcdc8
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0x2ac53d0 "abc"\0
SV = PV(0x2a9f150) at 0x2abcde0
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0x2ac53d0 "abc"\0

$x = \"$x" $x = \( my $container = $x );, Perl, COW.

+4

, :

my $string = 'abcefgh';
$string = \ "$string";

print $$string, "\n";
+1

Source: https://habr.com/ru/post/1686049/


All Articles