Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Testing for valid package names

by tobyink (Canon)
on Nov 25, 2013 at 21:56 UTC ( [id://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

Replies are listed 'Best First'.
Re^2: Testing for valid package names
by boftx (Deacon) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1064315]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-23 16:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found