【问题标题】:Shorthand for referring to Perl/Moose package names?引用 Perl/Moose 包名称的简写?
【发布时间】:2011-04-08 13:12:00
【问题描述】:

在 Python 和 Java 中,我们都有 import 以消除代码中完全限定的包/模块名称的重复。 Perl/Moose 中是否有任何等价物?我认为如果我们不必重复MyApp::Model::Item,它真的会让 Moose 更好用。相反,我想[somehow declare] MyApp::Model::Item; 稍后,只需参考Item。我能想到所有这些使用类名的用例......

  • extends 'Item';
  • with 'ItemRole';
  • Item->new(name => 'thing');
  • method foo(Item $xyz) { ... },与MooseX::Method::Signatures
  • $var->isa('Item');
  • try { ... } catch (DatabaseError $e) { ... },与TryCatch
  • $Item::SOME_PACKAGE_GLOBAL_VARIABLE

如果还没有这样的东西,我知道如何开始干净地实现它吗?我可以看到处理类名用作字符串的情况会很棘手。

【问题讨论】:

    标签: perl coding-style packages moose verbosity


    【解决方案1】:

    这一切都适用于aliased

    use aliased 'MyApp::Model::Item';
    use aliased 'MyApp::ItemRole';
    use aliased 'MyApp::Exception::DatabaseError';
    
    extends Item;
    with ItemRole;
    Item->new(name => 'thing');
    method foo (Item $xyz) { ... }
    $var->isa(Item);
    try { ... } catch(DatabaseError $e) { ... }
    

    这不是:

    $Item::SOME_PACKAGE_GLOBAL_VAR
    

    需要这样的东西似乎很少见,但我想它可以与namespace::alias 模块一起使用。

    【讨论】:

    • 太棒了!感谢您的快速回答!
    • 是的,我很少需要访问全局包,所以在这些情况下我可以忍受拼写名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多