tags:

views:

155

answers:

3

The documentation for ref() mentions several possible return values. I understand most of them, but not REF, IO, and LVALUE. How would I write Perl code to cause ref to return those values?

After reading the documentation on typeglobs and file handles, I came close for IO with this code:

open(INPUT, '<', 'foo.pl');
print ref(*INPUT{IO}), "\n";  # Prints IO::Handle

For REF and LVALUE I tried several bizarre constructions, but had no success.

+1  A: 
  1. 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

  2. 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)

DVK
+4  A: 

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.

Michael Carman
+12  A: 
JB
As delightful as the name `damn` is, it's unlikely that you'll want to remove the blessing. Use `Scalar::Util::reftype()` to see past the `bless` to the underlying reference type.
Michael Carman
Damn! I forgot about Scalar::Util! :-D Unfortunately, I can't seem to use it to make `ref` return "IO". I'll add a warning about `damn` not being serious; thanks for the reminder.
JB