The documentation for ref() mentions several possible return values. I understand most of them, but not REF
, IO
, and LVALUE
. How would
LVALUE
perl5.8 -e '{$a = "aaa"; $b = \substr($a, 0, 2); print "$$b\n"; print ref($b)."\n"}'
aa
LVALUE
This one is explained in perldoc -f ref
REF
perl5.8 -e '{$a = "aaa"; $b = \\$a; print ref($b)."\n"}'
REF
It's basically a reference to a value that is itself a reference.
Probably would have been better to do $b = \$a; $c = \$b; print ref($c)
Here's a quick and easy way to produce most of them:
use 5.010;
say 'SCALAR: ', ref \undef;
say 'ARRAY: ', ref [1..5];
say 'HASH: ', ref { key => 'value' };
say 'CODE: ', ref sub {};
say 'REF: ', ref \\undef;
say 'GLOB: ', ref \*_;
say 'LVALUE: ', ref \substr "abc", 1, 2;
say 'LVALUE: ', ref \vec 42, 1, 2;
say 'FORMAT: ', ref *STDOUT{FORMAT}; # needs declaration below
say 'IO: ', ref *STDIN{IO}; # actually prints IO::Handle
say 'VSTRING: ', ref \v5.10.0;
say 'Regexp: ', ref qr/./;
format =
.
REF is just a reference to another reference. LVALUE is a special case of a scalar that has an external influence if it is modified.
IO is the base type behind the handles, you can make it appear explicitely using Acme::Damn from CPAN. As noted by Michael Carman in the comments, you really shouldn't be unblessing objects — don't use in real code.
use Acme::Damn;
say 'IO: ', ref damn *STDIN{IO}; # really prints IO
The source for the ref
function also has bits of code to display "BIND" and "UNKNOWN", but there shouldn't be a way to get those without messing with the internals. Blead also has an interesting unblessed "REGEXP" (different from the "Regexp" above); if someone knows how to make ref
yield that...
REF
means that you have a reference to a reference:
my ($x, $y, $z);
$x = 1;
$y = \$x;
$z = \$y;
print ref $z; # REF
LVALUE
refs are rare, but you can get them from certain functions that return lvalues. substr
is one:
$x = 'abcdefg';
$y = \ substr($x, 0, 3);
print ref $y; # LVALUE
IO::Handle
objects are actually blessed IO
refs:
$x = *STDIN{IO};
print ref $x; # IO::Handle
print $x; # IO::Handle=IO(0x12345678)
I'm not sure how to get an IO
ref directly.