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

Hi all, I'm relatively new to Perl and having a problem when trying to use objects. I have a very simple BankAccount object that I'm trying to write methods for, but I keep getting the following error:

Not a HASH reference at BankAccount.pm line 21

And my code is below, with line 21 being the return statement in the getName method

sub new { my $class = shift; my $self = {name => $_[0], accountNo => $_[1], balance => 0, }; bless($self, $class); return $self; } sub getName { my $self = shift; return $self->{"name"}; }

Sorry if I'm being really ignorant; it seems like it should be so simple, but I have no idea what I'm doing wrong or how to correct it.

Replies are listed 'Best First'.
Re: OOP Beginner
by GrandFather (Saint) on Apr 26, 2012 at 02:30 UTC

    You don't show us enough code to be sure what is going wrong, but the following sample may contain the kernel of an "ahh" moment for you:

    use warnings; use strict; package BankAccount; sub new { my ($class, $name, $accountNo) = @_; return bless {name => $name, accountNo => $accountNo, balance => 0 +}, $class; } sub getName { my ($self) = @_; return $self->{name}; } package main; my $acct = BankAccount->new('Foo', '1234'); print $acct->getName();

    Prints:

    Foo

    There is nothing much different there than you were doing aside from what I consider to be better style. I suspect that you weren't calling the member correctly, but as you don't show that code I can't be sure.

    If the "Ahh" moment doesn't arrive for you show your equivalent of the code above.

    True laziness is hard work
Re: OOP Beginner
by locked_user sundialsvc4 (Abbot) on Apr 26, 2012 at 11:45 UTC

    Well, “Perl does objects just a little bit sideways.”   Here are the key notions:

    1. Perl lets you define packages of subroutines, such that you can use packagename and, having done so, call a routine in it.
    2. You can bless any variable to associate it with a package, so that $varname->subname(args...) becomes a call to a routine in the associated package (hand-waving here), which package Perl figures-out on its own; with $varname as the implied first argument.
    3. By convention (and nothing else), packages may contain a subroutine named new which creates a data structure, blesses it, and returns it to you.   This subroutine of course is called using a package syntax, referring to the desired package directly.

    And then... there is Moose ...   :-}