xslate / p5-Mouse

Lightweight class builder for Perl, as a subset of Moose
https://metacpan.org/release/Mouse
Other
46 stars 32 forks source link

Misleading error message when attribute is named 'import'. #61

Closed bbkr closed 8 years ago

bbkr commented 8 years ago

A.pm file:

package A;

use Mouse;

has 'import' =>  ( 'is' => 'ro', 'isa' => 'Int' );

1;

Usage:

$ perl -e 'use A;'
Invalid object instance: 'A' at -e line 1.
BEGIN failed--compilation aborted at -e line 1.

This error is tricky because syntax is correct (checked with perl -c) and bug can _not_ be reproduced as oneliner (perl -e 'package A; use Mouse; has "import" => ("is" => "ro", "isa" => "Int", "default" => 42); package main; print A->new->import' works just fine).

Mouse version 2.4.5.

charsbar commented 8 years ago

use A is roughly the same as require A; A->import. (see perlfunc, perlmod, and Exporter for details).

As you put has 'import' in the package A, when you use A, your "import" is called (A->import), and your "import" is an accessor which expects the caller is an object, the said error is triggered because the caller is a class ("A") in this case. If you do need to write has 'import', try require A or use A () not to call import method automatically.

In the one-liner you mentioned, package A is not actually "use"d, so A->import is not called either. If you write A.pm, and "use" it from an one-liner, you'll see the same error.

This is not a bug in Mouse (or Moose and its friends).

bbkr commented 8 years ago

Thanks for detailed explanation! I'm closing the issue.