Search code examples
perlread-eval-print-loop

re.pl: Variable cannot be used in print, but seems to keep reference, what happens


Using re.pl from Devel::REPL:

eddie@MYPC0:~$ re.pl
$ $a++
0
$ $a++
1
$ $a++
2
$ $a++
3
$ $a++
4
$ $a++
5
$ $a++
6
$ print $a
1
$ $a++
7

print $a prints 1 whether I initialize the variable or not. It seems it cannot print $a and it prints another sort of reference, also I don't understand if it loses the reference why is the value printed 1 instead of 0

Another test:

eddie@MYPC0:~$ re.pl
$ $a =1
1
$ print $a
1
$ $a++
1
$ print $a
1
$ $a++
2
$ $a++
3
$ print $a
1
$ $a++
4
$ print $a
1
$ $a++
5
$ $a
6
$ print $a
1

And yet another

eddie@MYPC0:~$ re.pl
$ my $a=0
0
$ print $a
1
$
$ $a
0
$

Solution

  • re.pl is showing you the return value of print. The print builtin "returns true" (i.e. 1) if it was able to successfully print something.

    andrew@goron:~$ re.pl
    $ $a = 42;
    42
    $ print $a;
    1
    $ print 0;
    1
    $ print "banana";
    1
    

    The reason you don't see any output from print itself is because Devel::REPL buffers output until it gets a newline:

    andrew@goron:~$ re.pl
    $ print "Hello";
    1
    $ print ", World!\n";
    Hello, World!
    1