How can I get the Perl ref () function to return REF, IO and LVALUE?

The documentation for ref () contains several possible return values. I understand most of them, but not REF , IO and LVALUE . How can I write perl code to call REF to return these values?

After reading the documentation for typeglobs and file descriptors , I approached IO with this code:

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

For REF and LVALUE I tried several fancy designs, but was unsuccessful.

+4
types perl
Sep 09 '09 at 13:54
source share
3 answers

Here you can easily and simply create 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 link to another link. 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 explicitly display with Acme :: Damn from CPAN . As Michael Carman pointed out in the comments, you really shouldn't be painless objects - don't use it 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 should be no way to get them, not mess with the internal elements. Blead also has an interesting unblessed "REGEXP" (different from "Regexp" above); if someone knows how to make ref output which ...

+14
Sep 09 '09 at 14:45
source share

REF means you have a link to a link:

 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 with IO refs:

 $x = *STDIN{IO}; print ref $x; # IO::Handle print $x; # IO::Handle=IO(0x12345678) 

I am not sure how to directly get the IO link.

+4
Sep 09 '09 at 14:17
source share
  • LVALUE

      perl5.8 -e '{$ a = "aaa";  $ b = \ substr ($ a, 0, 2);  print "$$ b \ n";  print ref ($ b). "\ n"} ' 
      aa 

    LVALUE

    This is explained in perldoc -f ref

  • REF

      perl5.8 -e '{$ a = "aaa";  $ b = \\ $ a;  print ref ($ b). "\ n"} ' 

    REF

    This is basically a reference to a value, which in itself is a reference. It would probably be better to do $b = \$a; $c = \$b; print ref($c) $b = \$a; $c = \$b; print ref($c)

+2
Sep 09 '09 at 14:15
source share



All Articles