http://qs321.pair.com?node_id=546890

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I recently encountered a bug in my code which took me quite a while to track down. I've created a minimal test case which demonstrates the problem. The tests were conducted with Perl 5.8.6 on Darwin and the original error was with 5.8.8 on FreeBSD.

The following code should be saved as Example/Foo.pm.

package Example::Foo; use strict; use warnings; use Example::Foo::One; my $obj = new Example::Foo; $obj->One(); sub new { my $self = shift; return bless {}, $self; } sub One { my $self = shift; my @caller = caller(); print "Example::Foo::One called, caller is $caller[0], line $calle +r[2]\n"; print "...Ref self is: ".(ref $self)."\n"; $self->Two(); } sub Two { my $self = shift; my $one = new Example::Foo::One('arg' => 'value'); ## Line of int +erest } 1;
And this should be saved as Example/Foo/One.pm:
package Example::Foo::One; use strict; use warnings; sub new { my $self = shift; print "Calling Example::Foo::One::new\n"; return bless {}, $self; } 1;
If you run this code, you will see that instead of calling Example::Foo::One::new(), the line in question calls Example::Foo::One(), with the error message 'Can't locate object method "Two" via package "arg" (perhaps you forgot to load "arg"?)', since it has shifted off the first argument to use as $self.

If the syntax of the line is changed to this:

my $one = Example::Foo::One->new('arg' => 'value');
the same error occurs (albeit with a different error message).

However, if you change the syntax to the very explicit:

my $one = Example::Foo::One::new('Example::Foo::One', 'arg' => 'value');
the correct method is called.

I am wondering why the original syntax did not call Example::Foo::One::new(), but instead called Example::Foo::One().