Explicitly quoting the class name rather than using a bareword (which is treated as a string) is one of three ways to avoid syntactic ambiguity. The Invoking Class Methods section of the perlobj documentation explains.
Because Perl allows you to use barewords for package names and
subroutine names, it sometimes interprets a bareword’s meaning
incorrectly. For example, the construct Class->new()
can be
interpreted as either 'Class'->new()
or Class()->new()
.In English,
that second interpretation reads as “call a subroutine named Class()
,
then call new()
as a method on the return value of Class()
.” If there
is a subroutine named Class()
in the current namespace, Perl will
always interpret Class->new()
as the second alternative: a call to
new()
on the object returned by a call to Class()
.
See this odd case in action with the demo below.
#! /usr/bin/env perl
use strict;
use warnings;
sub Type::Tiny { print "Returning Bogus\n" ; return "Bogus" }
sub Type::Tiny::new { print "Type::Tiny::new\n" }
sub Bogus::new { print "Bogus::new\n" }
my $class = "Type::Tiny";
Type::Tiny->new;
Type::Tiny::->new;
"Type::Tiny"->new;
$class->new;
Its output is
Returning Bogus
Bogus::new
Type::Tiny::new
Type::Tiny::new
Type::Tiny::new
The rest of the aforementioned documentation section shows how to protect against surprising behavior or inadvertent errors.
You can force Perl to use the first interpretation (i.e., as a
method call on the class named "Class"
) in two ways. First, you can
append a ::
to the class name:
Class::->new()
Perl will always interpret this as a method call.
Alternatively, you can quote the class name:
'Class'->new()
Of course, if the class name is in a scalar Perl will do the right
thing as well:
my $class = 'Class';
$class->new();
Applying to your question, all of the calls below are equivalent.
Type::Tiny::->new( … );
"Type::Tiny"->new( … );
my $class = "Type::Tiny";
$class->new( … );
Appending ::
to the end has the advantage of producing a helpful warning. Say you accidentally typed
Type::Tinny::->new;
That produces
Bareword "Type::Tinny::" refers to nonexistent package at ./try line 15.
Can't locate object method "new" via package "Type::Tinny" (perhaps you forgot to load "Type::Tinny"?) at ./try line 15.