Let's say I create a class named Bar
. The file Bar.pm
starts
package Bar;
To avoid colliding with other Bar
classes, I put the file in a subdirectory Foo
. So now, when I use the class, I have to write
use Foo::Bar;
My question is, do I need to change the name of the class to Foo::Bar
? In other words, do I need to change the first line of Bar.pm
to
package Foo::Bar;
? The problem is, if I do this, I now have to refer to the class as Foo::Bar
everywhere, e.g.
my $obj = Foo::Bar->new();
Foo::Bar->doClassMethod();
which is annoying (the same problem was discussed in this question), especially since I am fond of class methods.
Yes, you have to change the name of the package
to exactly match that of the use
.
If you think having a class name Bar
might conflict with other classes named Bar
then simply moving the file won't help. If your program eventually uses both Bar
and Foo::Bar
then both will have been loaded into the same namespace. At that point what happens to your program is anyone's guess.
If don't want to type long class names then you can use a variable to hold the name.
use My::Long::Class::Name::For::Bar;
my $bar_class = 'My::Long::Class::Name::For::Bar';
$bar_class->class_method(); # the same as My::Long::Class::Name::For::Bar->class_method()
You don't strictly need to (i.e. it's a style decision, not something the compiler enforces), but it is a good idea to follow the relevant guidelines set out in perlmod/perlnewmod to make the software easily distributable.
IOW, if long names bother you, get an editor with autocompletion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With