in reply to A Class inside a Perl script?

The use keyword wants to load the file test.pm. But you don't need the use statement at all, your program will work, because the test package has been initialized already in your script.

You should add package main; in front of your "main program" code, to avoid the confusion of namespaces.

Replies are listed 'Best First'.
Re^2: A Class inside a Perl script?
by harsha.reddy (Acolyte) on Jun 02, 2009 at 09:10 UTC
    I revamped the code to look like:
    #!/usr/bin/perl package test; use strict; use warnings; use Switch; sub new { my $class = shift; my $self = { host => "127.0.0.1", server => "localhost", username => "user1", password => "passwd", name => undef, operation => undef }; bless $self, 'Person'; return $self; } sub echo { my $self = shift; print $self->host; } 1; package main; $eco = test->new(); $eco->echo();

    No luck

    Can't locate object method "echo" via package "Person" at ./test line 34.

    Is the error that I am getting.
    Why is it taking the name of the package as "Person" instead of "test"?
    My perl is: perl, v5.8.8 built for i386-linux-thread-multi
    on RHEL5

      bless tells you why your program is looking for a package named Person. And don't, ever, use Switch. It is a bad idea to even mention in your source code, because it has nasty side-effects. If you use Perl 5.10, you can use the new given keyword instead, otherwise just use a chain of if..elsif..else or a dispatch table.

        ... or even use an instance of the poor mans switch

        A user level that continues to overstate my experience :-))
        And don't, ever, use Switch. It is a bad idea to even mention in your source code, because it has nasty side-effects.
        Could you expand on that or provide me with a link where I can find more on this?

      Why is it taking the name of the package as "Person" instead of "test"?

      You are given the class name for bless as "Person" thats why .

      bless $self, 'Person';
      Vinoth,G
      Direct answers were already told by other monks, if you need insight on OO perl, see perlmod, perltoot, perlmodlib
      and this Object Oriented Perl can also guide you.

      Vivek
      -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.