in reply to bless array of hashes correct get method wrong
You should call it with $itemref, this is the variable holds the object. Even if this was the case, you would get error because in your method definition, you use an array reference but dereference it as HASH.
The $_[0] is the first element of @_, which holds parameters passed in to methods/subroutines. In a method, $_[0] is supposed to be the object itself, hence the use of $self as a convetional variable name.
I assume that you (hopefully) have a sort of this structure:
# simplified version my @array = ({id=>1, name=>'Linux'}, {id=>2, name=>'Perl'}); my $self = [@array]; bless $self, $class
Remember, the first argument to method is the object itself. Your object is a reference to an ARRAY so you can't dereference it as HASH. Instead, you want something like this.
sub get_desc { my($self, $idx) = @_; return $self->[0]{_description}; }
And you call it like this,
my $item = Item::Item->new('some record id'); print $item->get_desc(0);
You should stay with your object after creating it, don't dereference to use it to call an object method.
So, you have the Item::Item object reference in $itemref. The statement,my $itemref = Item::Item->new( "10056" );
@item = @$itemref; print $item[0]->{_description};
gave you the right thing because you treated it as data structure. But remember, your object is $itemref. So stick with it whenever you want to use it as object.
When I first learned about OOP (object oriented Perl :-), I found perlobj and perltoot as good introductions and enjoyful to read.
Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: bless array of hashes correct get method wrong
by peterb (Novice) on Apr 20, 2007 at 16:57 UTC | |
by peterb (Novice) on Apr 20, 2007 at 18:32 UTC |