Search code examples
perlcoding-styleclassnamebareword

Why do some users quote classnames in Perl?


Looking at Type::Tiny, I see that the class name in the call to Type::Tiny->new is quoted in the official docs,

my $NUM = "Type::Tiny"->new(
   name       => "Number",
   constraint => sub { looks_like_number($_) },
   message    => sub { "$_ ain't a number" },
);

Why is this? Is this mere style? Is there any performance ramifications for this practice?


Solution

  • Take a simpler example

    package Foo { sub new { die 7  } };
    package Bar { sub new { die 42 } };
    sub Foo { "Bar" }
    Foo->new();
    

    In the above example, the constant Foo resolves to "Bar", so so this calls "Bar"->new not "Foo"->new. How do you stop the subroutine from resolving? You can quote it.

    "Foo"->new();
    

    As for the performance implication, things are not made worse by using a string rather than a bareword. I've confirmed the optree generated by O=Deparse is the same. So as a general rule, it seems it's better to quote the Classnames if you value correctness.

    This is mentioned in Programming Perl, (sadly in the context of indirect method invocation)

    ... so we'll tell you that you can almost always get away with a bare class name, provided two things are true. First, there is no subroutine of the same name as the class. (If you follow the convention that subroutine names like new start lowercase and class names like ElvenRing start uppercase, this is never a problem). Second, the class been loaded with one of

    use ElvenRing;
    require ElvenRing;
    

    Either of these declarations ensures that Perl knows ElvenRing is a module name, which forces any bare name like new before the class name ElvenRing to be interpreted as a method call, even if you happen to have declare a new subroutine of your own in the current package.

    And, that makes sense: the confusion here can only happen if your subroutines (typically lowercase) have the same name as a class (typically uppercase). This can only happen if you violate that naming convention above.

    tldr; it is probably a good idea to quote your classnames, if you know them and you value correctness over clutter.

    Side note: alternatively you can stop resolution of a bareword to a function by affixing a :: to the end of it, for example in the above Foo::->new.


    Thanks to Ginnz on reddit for pointing this out to me, and to Toby Inkster for the comment (though it didn't make sense to me on first read).