in reply to Re^2: "use"ing from dynamic namespace
in thread "use"ing from dynamic namespace

Would there be anything wrong with doing config_module in the base class as: ...

...the only problem is it wouldn't work ;) — at least not with perrin's code snippet.  One thing is that if you use require with a string (as opposed to a bareword), it must be a valid path fragment (i.e. / in place of ::), inlcuding the trailing .pm. The other thing is that when you declare config_module() in the base class, __PACKAGE__ would always be Base::Module, but the point of the exercise was to load different config variants (associated with Foo, Bar, etc.).

Replies are listed 'Best First'.
Re^4: "use"ing from dynamic namespace
by pobocks (Chaplain) on Dec 02, 2008 at 23:37 UTC

    I suspected something like that.

    I guess my next try would be:

    sub config_module { $self = shift; return ref($self) . '/Config.pm'; }
    And just always calling it as a method?

    for(split(" ","tsuJ rehtonA lreP rekcaH")){print reverse . " "}print "\b.\n";

      ...almost there :)   but you'd still have to get rid of the "::" in case of a package name like "Foo::Module". Also, you could write ref($self) || $self, in which case you could call load_config on both the class or an object instance.

      #!/usr/bin/perl package Base::Module; sub load_config { my $class = shift; my $module = $class->config_module; print "about to require $module\n"; #require $module; } sub config_module { $self = shift; my $pkg = ref($self) || $self; $pkg =~ s#::#/#g; # optionally remove "/Module" # $pkg =~ s#/[^/]+\z##; return "$pkg/Config.pm"; } package Foo::Module; use base qw(Base::Module); sub new { return bless {}, shift; } package main; Foo::Module->load_config(); Foo::Module->new()->load_config(); __END__ $ ./727519.pl about to require Foo/Module/Config.pm about to require Foo/Module/Config.pm

      BTW, the sub config_module would work the same way when declared in Foo::Module, though - if I'm understanding you correctly - your idea was to put it in the base class...  (Actually, it would first be looked up in Foo::Module, and only then, when this fails, in Base::Module (via inheritance).)