Are there equivalents to Ruby's method_missing in other languages?

前端 未结 15 1641
渐次进展
渐次进展 2020-12-08 08:00

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:

15条回答
  •  眼角桃花
    2020-12-08 08:49

    Perl has AUTOLOAD which works on subroutines & class/object methods.

    Subroutine example:

    use 5.012;
    use warnings;
    
    sub AUTOLOAD {
        my $sub_missing = our $AUTOLOAD;
        $sub_missing =~ s/.*:://;
        uc $sub_missing;
    }
    
    say foo();   # => FOO
    

    Class/Object method call example:

    use 5.012;
    use warnings;
    
    {
        package Shout;
    
        sub new { bless {}, shift }
    
        sub AUTOLOAD {
            my $method_missing = our $AUTOLOAD;
            $method_missing =~ s/.*:://;
            uc $method_missing;
        }
    }
    
    say Shout->bar;         # => BAR
    
    my $shout = Shout->new;
    say $shout->baz;        # => BAZ
    

提交回复
热议问题