UNIVERSAL::ref(3)

🌸 NAME 🌸

Okay so bestie, welcome to UNIVERSAL::ref(3) β€” straight out of the User Contributed Perl Documentation corner of the universe. This module is literally called UNIVERSAL::ref, and its whole vibe is: turns ref() into a multimethod. No cap.

✨ SYNOPSIS ✨

Here’s the iconic little demo where Wrapper pretends to be Thing, and the ref check says true:

# True! Wrapper pretends to be Thing.
ref( Wrapper->new( Thing->new ) )
  eq ref( Thing->new );

package Thing;
sub new { bless [], shift }

package Wrapper;
sub new {
    my ($class,$proxy) = @_;
    bless \ $proxy, $class;
}
sub ref {
    my $self = shift @_;
    return $$self;
}

πŸ’– DESCRIPTION πŸ’–

This module changes the behavior of the builtin ref(). If ref() is called on an object that has requested an overloaded ref, then the object’s ->ref method gets called and its return value is used instead. That’s the whole trick, and it’s honestly iconic.

πŸŽ€ USING πŸŽ€

To enable this feature for a class, put use UNIVERSAL::ref in your class. Here’s a sample proxy module:

package Pirate;
# Pirate pretends to be a Privateer
use UNIVERSAL::ref;
sub new { bless {}, shift }
sub ref { return 'Privateer' }

Anywhere you call ref($obj) on a Pirate object, it will allow Pirate to lie and pretend to be something else. iykyk πŸ΄β€β˜ οΈ

πŸ¦‹ METHODS πŸ¦‹

πŸ“₯ import

A pragma for ref()-enabling your class. This adds the calling class name to a global list of ref()-enabled classes.

package YourClass;
use UNIVERSAL::ref;
sub ref { ... }

πŸ“€ unimport

A pragma for ref()-disabling your class. This removes the calling class name from a global list of ref()-enabled classes.

πŸ’€ TODO πŸ’€

  • Currently UNIVERSAL::ref must be installed before any ref() calls that are to be affected.
  • I think ref() always occurs in an implicit scalar context. There is no accomodation for list context.
  • UNIVERSAL::ref probably shouldn’t allow a module to lie to itself. Or should it?

🌈 ACKNOWLEDGEMENTS 🌈

  • ambrus for the excellent idea to overload defined() to allow Perl 5 to have Perl 6’s "interesting values of undef."
  • chromatic for pointing out how utterly broken ref() is. This fix covers its biggest hole.

πŸ‘‘ AUTHOR πŸ‘‘

Joshua ben Jore - jjore@cpan.org

πŸ“œ LICENSE πŸ“œ

The standard Artistic / GPL license most other perl code is typically using.


Okay that’s the whole page, bestie. Source/version: perl v5.42.0, date: 2024-03-04, manual: UNIVERSAL::ref(3). Mwah πŸ’‹πŸ«Ά

πŸ“¦ where this page comes from