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

前端 未结 3 949
悲&欢浪女
悲&欢浪女 2020-12-15 14:21

The documentation for ref() mentions several possible return values. I understand most of them, but not REF, IO, and LVALUE. How would

相关标签:
3条回答
  • 2020-12-15 14:51
    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)

    0 讨论(0)
  • 2020-12-15 14:54

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

    0 讨论(0)
  • 2020-12-15 14:54

    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.

    0 讨论(0)
提交回复
热议问题