Skip to content

Instantly share code, notes, and snippets.

@briandfoy
Created July 9, 2025 17:12
Show Gist options
  • Save briandfoy/fab57a8ea95ba9f1b865b0aec21a8b46 to your computer and use it in GitHub Desktop.
Save briandfoy/fab57a8ea95ba9f1b865b0aec21a8b46 to your computer and use it in GitHub Desktop.
A demonstration of some Perl method calling features
#!/usr/bin/perl
{
package Parent;
sub bar { print "Parent: $_[0]" . "\n" }
}
{
package Foo;
use parent qw(Parent);
sub bar { print $_[0] . "\n" }
}
print "# the invocant\n";
my $string = 'Foo';
$string->bar;
my $blessed = bless {}, $string;
$blessed->bar;
print "\n# the method\n";
my $method = 'bar';
$string->$method;
$blessed->$method;
# in SUPER, the virtual namespace that looks in @ISA
# this looks in the current package, not the package of
# the object. For this to work in main::, main needs a
# parent class
print "\n# main super class\n";
our @ISA = qw(MainSuper);
{
package MainSuper;
sub bar { print "MainSuper: $_[0]" . "\n" }
}
$string->SUPER::bar();
$blessed->SUPER::bar();
# Now start in Foo instead, and get what you probably wanted.
# Check out the SUPER module on CPAN that changes this oddity.
print "\n# Foo super class\n";
{
package Foo;
$string->SUPER::bar();
$blessed->SUPER::bar();
}
# Now, specify any sub you like:
print "\n# arbitrary sub\n";
sub quux { print "quux: @_" . "\n" }
$string->main::quux( 3, 7, 1 ); # really quux( $string, 3, 7, 1 )
$blessed->main::quux( 7, 3, 1 ); # really quux( $blessed, 7, 3, 1 )
# compare this with can, which returns a code ref is it can resolve
# that method, but where you have to supply the first argument yourself
print "\n# can\n";
my $coderef = $blessed->can('bar');
$coderef->($blessed);
$coderef->($string);
# but CORE is another package, and its does the same thing you just
# saw in main. This is a v5.16 thing, but it's using the
{
print "\n# CORE::substr\n";
if( $] < 5.016 ) { print "v5.16 needed for core, this is $]"; last}
print $string->CORE::substr( 0, 2 ), "\n"; # really substr( $string, 0, 2 )
print $blessed->CORE::substr( 3, 4 ), "\n"; # really substr( $blessed, 3, 4 )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment