sman has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have a class called My::Foo and want to create its instance like this:
use My::Foo; my $obj = My::Foo->new( name => 'jeff' );
Do I have to use its fully-qualified name 'My::Foo' to call new()?
Can I just shortly use Foo->new() ?

thanks.

Replies are listed 'Best First'.
Re: Question about new()
by ikegami (Patriarch) on Jan 22, 2010 at 07:11 UTC

    No. new is in package My::Foo (or one of its descendants), not in unrelated package Foo. You seem to missing that Foo is a fully qualified package name.

    Now, if the current package had a function named Foo that returned the string "My::Foo", ...

      This was the first thing I thought of as well. My second thought was to add it through Exporter. My third thought was "eeewwww".

      It is said that "only perl can parse Perl." I don't even come close until my 3rd cup of coffee. --MidLifeXis

Re: Question about new()
by SpiceMan (Sexton) on Jan 22, 2010 at 09:37 UTC

    Or you can use namespace::alias

    use namespace::alias "My::Foo::Bar::Baz", "Baz"; Baz->new(); # My::Foo::Bar::Baz->new() Baz::Quux->something(); # My::Foo::Bar::Baz::Quux->new()
      After installing this module <namespace::alias> and put this line in my class
      use namespace::alias 'Result::Users';
      My catalyst develop server is supposed to reboot but only display this message :
      Attempting to restart the server
      and pause to go any further.
      Do you know why?
Re: Question about new()
by Anonymous Monk on Jan 22, 2010 at 07:20 UTC
    as
    use as; # activate 'use' magic use Very::Long::Module::Name as => 'Foo'; use Other::Long::Module::Name qw(parameters being passed), as => ' +Bar'; my $foo = Foo->new; # blessed as Very::Long::Module::Name my $bar = Bar->new; # blessed as Other::Long::Module::Name
      Thanks. Your solution works for me. But, my eclipse with EPIC complains on this line :
      use Result::Users as => 'Users';
      with this error message : 'Can not locate Result/Users.pm in @INC....'.

      I know it's not a big deal, but do you know why?
        I dont use eclipse, but I would guess because Result/Users.pm is not in @INC ... if that is not the case, then its eclipse bug.