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

I have created a class and tried to create an object with that class, but I keep having this error

Can't locate object method "new" via package "Switch" at test.pl line 5.

Here's the code:

class Code:
use Net::Telnet(); package Switch; sub new { my $class = shift; my $location = shift; my $ip = shift; my $self = {}; bless $self, $class; return $self; } 1;
program code
use Switch; use strict; use warnings; my $switch = Switch -> new();
does anyone know how to fix this error? Thanks in advance

Replies are listed 'Best First'.
Re: Error with creating new objects
by GrandFather (Saint) on Jun 25, 2012 at 03:25 UTC

    I suspect you are falling foul of the core Switch module. A simple test would be to change the name of your module to TelnetSwitch or some other appropriate name.

    True laziness is hard work
      or add  use Data::Dump; dd \%INC, \@INC; to see which file is being loaded (Switch.pm)
Re: Error with creating new objects
by NetWallah (Canon) on Jun 25, 2012 at 03:21 UTC
    The Namespace is Switch::. Try:
    my $switch = Switch:: -> new();
    Although, your code works fine for me (perl 5.14).

    Update - I did reproduce your problem - the issue is what Grandfather (++) says, below.

    The recommendation to use NameSpace:: stands.

                 I hope life isn't a big joke, because I don't get it.
                       -SNL

Re: Error with creating new objects
by mrguy123 (Hermit) on Jun 25, 2012 at 07:13 UTC
    Is the name of the PM file Switch.pm or Code.pm? If the name of the file is not Switch.pm it explains the error. Also, as mentioned above, it would be wiser to use a module with a lesser known name than Switch.


    Very funny, Scotty. Now beam down my clothes.