in reply to Capitalized subroutine names and packages
My shot at an explanation: I'm guessing the -> operator will only do a method call when the left operand is either a bareword or a scalar (a package name or a ref). But since you have Bar defined as a sub in main's symbol table, it can never be a bareword, so it tries to evaluate it to a scalar: i.e., by calling the subroutine Bar. You end up with a scalar "Foo" which is a package name, so you get the package method call equivalent to Foo->new
I like this because now you can hijack stuff like this:
Create a subclass of CGI without changing your CGI->method calls in the client code! Just import the CGI subroutine to the caller's namespace.Stealer.pm: package Stealer; use base 'Exporter'; @EXPORT = qw/CGI/; sub CGI { return 'Stealer'; } sub new { print "Stolen!"; } script.pl: use CGI; use Stealer; my $q = CGI->new;
Update: In your code, if you wrap the declaration of the Bar subroutine in an eval q{...} block, the last line will compile "Bar" as a bareword string instead of a subroutine call, and the output will be "Bar's constructor called"
blokhead
|
|---|