Hameed has asked for the wisdom of the Perl Monks concerning the following question:
It maybe a simple thing, but I seem to have hit a brick wall.
I have a very simple class and in the constructor, I am creating a hash that is holding references to subs which are members of the same class as well.
see below:Now, when I call total_sold from another method in this class (get_stats in this case), '$this' is undefined in total_sold and '$this->dosomething' returns an error 'Can't call method "dosomething" on an undefined value at EOYStats.pm line 37.'package EOYStats; use strict; use warnings; use Data::Dumper; sub new { my $class = shift; my $this = bless {}, $class; $this->{ACT} = shift; %{ $this->{ACTIVITIES} } = ( 'Sale' => { 'func' => \&total_sold, 'datefield' => "date_sold", }, 'Purchae' => { 'func' => \&total_bought, 'datefield' => "date_bought", }, ); return $this; } sub get_stats { my $this = shift; my $arg = shift; $this->{ACTIVITIES}->{$this->{ACT}}->{'func'}->($arg); } sub total_sold { my $this = shift; my $arg = shift; $this->dosomething(); } sub total_bought { my $this = shift; my $arg = shift; # Do stuff.... } sub dosomething { my $this = shift; print "This is test...\n"; } return 1;
There is no real need to have these methods in a hash. I can simply write conditions in the get_stats and call the methods accordingly, but I wanted to try and see if this worked.
so is it really ridiculously bad idea to do this or is it not possible or simply silly thing to do?
Sorry if this is too confusing.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Hash of subroutines as member of a class
by tangent (Parson) on Sep 30, 2014 at 01:52 UTC | |
|
Re: Hash of subroutines as member of a class
by GrandFather (Saint) on Sep 30, 2014 at 02:44 UTC | |
|
Re: Hash of subroutines as member of a class
by Athanasius (Archbishop) on Sep 30, 2014 at 03:20 UTC | |
by Hameed (Acolyte) on Sep 30, 2014 at 03:47 UTC |