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

hai monks

i tried the following example to learn the class .
but it shows the following error.
Can't call method "name" on an undefined value at ClassWithPrg.pl line 17.
plz help me to rectify this error.
Source code

#!/usr/bin/perl -w sub new() { my $self={}; $self->{FORM_VAR}=undef; bless($self); return $self->{FORM_VAR}; } sub name() { $self->{FORM_VAR}=shift; print "Using the constructor\n\n\n"; return $self->{FORM_VAR}; } + $obj=main->new(); $var=$obj->name("KALAI"); print "Here ::: $var\n";
thankyou

Replies are listed 'Best First'.
Re: Regarding Perl Class Object
by Sidhekin (Priest) on Feb 22, 2007 at 06:46 UTC

    Your new method is returning $self->{FORM_VAR}, which is undefined. You want to return $self, your newly created and blessed object.

    And you want to lose those prototypes.

    Oh, and you want to use strict.

    ... which will lead you to an error in your name method, where $self is undeclared and undefined. You'll want my $self = shift;

    ... and then you might want to look into using packages other than main. :)

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

Re: Regarding Perl Class Object
by klekker (Pilgrim) on Feb 22, 2007 at 08:21 UTC
Re: Regarding Perl Class Object
by Moron (Curate) on Feb 22, 2007 at 12:36 UTC
    The most burning issue to me is that your class is anonymous. The class and all its methods should be defined in a separate Whatever.pm file, which contains the first line "package Whatever;". The magic line with the -w followed by the use strict;pragma should instead be placed in the main program which itself should indeed be a .pl file - it won't get executed if placed within the .pm file where your class should be defined.

    -M

    Free your mind

      Sorry, but that reply is a little misleading.

      editi's class isn't anonymous, it's established in the default package main. While that is unusual, there's nothing wrong with it in principle. I do share the concern that it looks like the Author is not familiar with the standard way of establishing classes in dedicated packages.

      But to do that, it is by no means necessary to put the class code in an extra file. You can very well define a named class inside the main program. For tests and experiments you save a bit of potential hassle that way (in exchange for a smaller bit of different hassle).

      Thirdly, you are right that #!/path/to/perl -w isn't effective in a module file. But that isn't the modern way of switching on warnings anyway. use warnings works in main programs as well as in module files (and is needed in both, because its scope is lexical).

      Anno

      [update: corrected attribution]

      A reply falls below the community's threshold of quality. You may see it by logging in.
A reply falls below the community's threshold of quality. You may see it by logging in.