It looks simple, but I can't find but ugly solutions:
PROBLEM
Assume that $name contains some alphanumeric string, and that I can open the file "$name.pm" (which means that under windows, the file could have been created under a name which differs from $name by upper/lower case letters, since Windows is not case sensitive).
Question: Assuming that if some function I am going to call later, would do a require and import on that file, will it be, or will it not be the case, that a package with the name $name will exists?
EXAMPLE
Say, I have three files:
and I go through the files like this:# This is file Test1.pm package Test1; # End of File # This is file test2.pm package Test2; # End of File # This is file Test3.pm package Test; # End of File
I would like to have printed:foreach my $name (qw(Test1 test2 Test3)) { unless(file_defines_package_of_same_name($name)) { print "$name\n"; } }
I would like to have test2 printed, because the package defined in test2.pm is Test2, not test2. I would like to have Test3 printed, because the package defined in Test3.pm is Test, not Test3. The problem is how to write the function file_defines_package_of_same_name.test2 Test3
IDEAS
I have already thought about ways to solve this, but all my solutions seem to be unnecessarily complicated. Here are the two ideas I had so far:
1. Manually open the file and grep for "package $name". Disadvantage: Might give false positive if the line in question appears within a comment or string.
2. Tentatively require the module, then inspect the Perl symbol table for the presence of a $name:: hash:
I might get false positives if package $name already existed before, but this is a restriction I can live with. I don't know however about what other nasty consequences this might have to my current package.# NOT TESTED!!!! sub file_defines_package_of_same_name { my $name=shift; eval { require $name; { no strict; $name->import(); } # I guess I don't need this, do I? defined(eval 'scalar(keys(%'.$name.'::))'); } }
RATIONALE
Why do I want to do such a weird test? I am maintaining an application which uses Class::MixinFactory. This module exits Perl if it tries to load a mixin module, and the mixin name (which ends up being a module name) does not match the package name defined in the module.
Hence, a third option for my problem would be to fix Class::MixinFactory, so that instead of exiting, it would throw an exception; but since this is a highly complex module, I would prefer to catch the error before calling MixinFactory, provided there is an easy way to do it.
In reply to Finding out whether a module contains a certain package by rovf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |