Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Testing for valid package names

by tobyink (Abbot)
on Nov 25, 2013 at 21:56 UTC ( #1064315=note: print w/ replies, xml ) Need Help??


in reply to Testing for valid package names

Module::Runtime is probably what you want to use for this. Here are the relevant parts...

sub _is_string($) { my($arg) = @_; return defined($arg) && ref(\$arg) eq "SCALAR"; } our $module_name_rx = qr/[A-Z_a-z][0-9A-Z_a-z]*(?:::[0-9A-Z_a-z]+)*/; sub is_module_name($) { _is_string($_[0]) && $_[0] =~ /\A$module_name_rx\z/o; }

This is more restrictive than your current check - in particular it excludes all non-ASCII word characters. This is because Unicode file names are handled pretty inconsistently across different file systems and Perl versions.

Note that this is really a module name check; not a package name check. Modules are files on the filesystem; packages are namespaces. Package names are a lot more relaxed than module names; for example, the space character can be used as a package name:

perl -E'*{" ::foo"} = sub {42}; say " "->foo'
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name


Comment on Re: Testing for valid package names
Select or Download Code
Re^2: Testing for valid package names
by boftx (Chaplain) on Nov 25, 2013 at 22:08 UTC

    Thanks! That was the regex I was coming up with, but seeing it in use is even better. And I hadn't considered the Unicode aspect. :)

    It helps to remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1064315]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (11)
As of 2014-09-30 13:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (372 votes), past polls