jkeenan1 has asked for the wisdom of the Perl Monks concerning the following question:
I would like to be able to refactor out all the code shared by the two subs but am wondering what the best way to handle the differences. Some pseudo-code:
sub alpha { my $self = shift; ... foreach ... if ... if ... if ... push @foo, [ @bar ]; } } } else { push @foo, [ @bar ]; } } push @foo, [ @bar ]; return \@foo; } sub beta { my $self = shift; ... foreach ... if ... if ... if ... push @foo, [ @bar ] if $self->{baz} eq $gamma; } } } else { push @foo, [ @bar ] if $self->{baz} eq $gamma; } } push @foo, [ @bar ] if $self->{baz} eq $gamma; return \@foo; }
Except for the difference between
push @foo, [ @bar ];
and
push @foo, [ @bar ] if $self->{baz} eq $gamma;
... the two subroutines are identical. Which implies that I could and should refactor out the common code into an internal subroutine. I would like to have a structure like this:
sub alpha { my $self = shift; my $coderef = sub {1}; return $self->_internal_sub($coderef); } sub beta { my $self = shift; my $coderef = sub {$self->{baz} eq $gamma}; return $self->_internal_sub($coderef); } sub _internal_sub { my $self = shift; my $coderef = shift; ... foreach ... if ... if ... if ... push @foo, [ @bar ] if &$coderef; } } } else { push @foo, [ @bar ] if &$coderef; } } push @foo, [ @bar ] if &$coderef; return \@foo; }
... but of course the values of $self-baz and $gamma are unknown at the time of assignment to $coderef in beta().
I have a feeling I'm missing something obvious here. Can any of the monks suggest a remedy? Thanks.
Jim Keenan
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Seek Help Refactoring
by CountZero (Bishop) on Apr 02, 2006 at 21:30 UTC | |
by jkeenan1 (Deacon) on Apr 03, 2006 at 00:41 UTC | |
|
Re: Seek Help Refactoring
by GrandFather (Saint) on Apr 02, 2006 at 21:55 UTC | |
|
Re: Seek Help Refactoring
by Tanktalus (Canon) on Apr 02, 2006 at 21:55 UTC | |
|
Re: Seek Help Refactoring
by dragonchild (Archbishop) on Apr 03, 2006 at 00:00 UTC | |
by moklevat (Priest) on Apr 03, 2006 at 14:13 UTC | |
|
Re: Seek Help Refactoring
by xdg (Monsignor) on Apr 02, 2006 at 21:25 UTC | |
by jkeenan1 (Deacon) on Apr 03, 2006 at 00:49 UTC | |
|
Re: Seek Help Refactoring
by liverpole (Monsignor) on Apr 02, 2006 at 22:04 UTC | |
|
Re: Seek Help Refactoring
by TedPride (Priest) on Apr 02, 2006 at 23:42 UTC | |
|
Re: Seek Help Refactoring
by codeacrobat (Chaplain) on Apr 02, 2006 at 22:43 UTC |