Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl class naming convention

Tags:

perl

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.

like image 588
shawkinaw Avatar asked Feb 29 '12 18:02

shawkinaw


3 Answers

Yes, you have to change the name of the package to exactly match that of the use.

like image 189
tchrist Avatar answered Sep 23 '22 09:09

tchrist


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()
like image 24
Ven'Tatsu Avatar answered Sep 22 '22 09:09

Ven'Tatsu


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.

like image 34
daxim Avatar answered Sep 19 '22 09:09

daxim