++ for this interesting observation. I guessed wrong at first because I thought the
sub Bar would have had to have been prototyped as
sub Bar() for it to get called in the last statement. Well, I was wrong there, but then I thought for sure if I prototyped it as
sub Bar($), Perl would see that
Bar alone is not a valid function call, so while examining the last statement it would try to interpret it as a package name instead. Nope, that gives a compile error.
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:
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;
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.
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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.