Stucked has asked for the wisdom of the Perl Monks concerning the following question:
Im new to objects and not that old at hashes so I thought Id
confusicate myself totally trying to make a hash of objects.
I would like to access an element from my list of objects in the following example
using its object name, so I made a hash of objects.
However Ive obviously made a mess somewhere as I keep getting
the error "Can't call method "print" on unblessed reference...
A helping hand is worth 2 in the bush
#!/apps/perl/5.8.3/bin/perl -w use strict; ### PACKAGE ### package Register; sub new { my ($class) = @_; my $self = { _regName => undef, _regID => undef, }; bless $self, $class; return $self; } sub regName { my ( $self, $regName ) = @_; $self->{_regName} = $regName if defined($regName); return $self->{_regName}; } sub regID { my ( $self, $regID ) = @_; $self->{_regID} = $regID if defined($regID); return $self->{_regID}; } sub print { my ($self) = @_; if (defined $self->regName) { printf ("%s\n",$self->regName) + }; if (defined $self->regID) { printf ("%s\n",$self->regID) + }; } ################### my @Regs; $Regs[0] = new Register(); $Regs[1] = new Register(); $Regs[0]->regName("CLKEN"); $Regs[0]->regID("REG3456"); $Regs[1]->regName("IRQEN"); $Regs[1]->regID("REG4444"); # I want to access the register based on regName and dont want to # search the array each time for my register. So make a hash as follow +s my %reg_hash; foreach my $reg (@Regs) { $reg_hash{$reg->regName()} = [] unless exists $reg_hash{$reg->regNa +me()}; push @{$reg_hash{$reg->regName()}}, $reg; } # now to access a register object from the hash my $curr_reg; $curr_reg = new Register(); $curr_reg = \$reg_hash{IRQEN}; $curr_reg->print; # ERROR!! Can't call method "regID" on unblessed re +ference at ./hash_of_objects.pl line 54 $curr_reg = $Regs[0]; $curr_reg->print; # This line is ok, but seems the same to me ? 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: hash of objects
by kyle (Abbot) on Mar 22, 2007 at 20:19 UTC | |
by Stucked (Initiate) on Mar 23, 2007 at 07:44 UTC |