Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1064315]
and the sunlight beams...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2017-08-16 23:06 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (276 votes). Check out past polls.