I
I
Ivan Komarov2011-07-25 20:06:02
Perl
Ivan Komarov, 2011-07-25 20:06:02

Links in perl

Please explain why the result of running this program:


$a = 'a';
$b = \$a;
$c = $$b;
$a = 'bb';
print "$$c\n";
print "$c\n";


like this one:
bb
a

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin Vlasov, 2011-07-25
@FreeTibet

After the third line, $c is the string 'a'. $$c is the expansion of a variable with a name equal to the content of $c - that is, the variable $a, which already contains the value 'bb' by the time it is printed. Accordingly, 'bb' is printed as the first line. The second line prints just the contents of $c, ie 'a'.

R
rPman, 2011-07-25
@rPman

As I understand it, there is an error in the second line, not '\$a' but '&$a'?

$a = 'a'; // variable a value a
$b = &$a; // variable b value will always be equal to the value of variable a (i.e. now it's 'a')
$c = $$b; // variable c is equal to the value of the variable whose name is in variable b, i.e. is equal to the value of the variable a, so it is equal to 'a'
$a = 'bb'; // variable a changes value to 'bb', so variable b now also returns 'bb'
print "$$c\n"; // prints the value of the variable whose name is in the variable c, now the value is a, so the result of the variable with the name a is now 'bb'
print "$c\n"; // value of variable c is 'a'

F
FloppyFormator, 2011-07-26
@FloppyFormator

I like the behavior of the pearl in the strict much more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question