Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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
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 web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2015-11-25 10:32 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (673 votes), past polls