Re: A small programming problem



Richard Harter wrote:
On Wed, 04 Oct 2006 00:52:43 GMT, "John W. Krahn"
<someone@xxxxxxxxxxx> wrote:

Richard Harter wrote:
[snip problem statement]
$ perl -le'
$a0 = [ "b0", "b1" ];
$s1 = [ $a0, "a1" ];
$S = [ "s0", $s1, "s2" ];

$P = do {
my $previous;
sub {
my $list = shift;
for my $item ( @$list ) {
$P->( $item ), next if ref $item eq "ARRAY";
$item .= $previous;
$previous = $item;
}
}
};

[snip data dumper]

If I follow this correctly (and I doubt it, perl is not one of my
languages) you're doing the same thing that mensanator did with the
python solution - you're neglecting the 'state' issue. An explanation
in words would be helpful.

The variable $P is a closure[1,2] and the previous 'state' is stored in the
$previous variable which is lexically scoped so that it is only available to
the closure. HTH



1. http://en.wikipedia.org/wiki/Closure_(computer_science)
2. http://faq.perl.org/perlfaq7.html#What_s_a_closure_


John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall
.



Relevant Pages

  • Re: Shifting Away
    ... are there two armed camps of Perl monks throwing gazillion megawatt ... daily at shift change and shout "When should I use an en dash?" ... become a bit less paranoid now but it's hard to let go of formal params. ... in the argument list and the sub could still change that. ...
    (comp.lang.perl.misc)
  • Re: New to Perl, OOP inheritance
    ... I'm new to Perl (from C, JavaScript, Ruby) and going through the Camel ... my $invocant = shift; ... sub toString { ...
    (comp.lang.perl.misc)
  • Re: reflection in perl
    ... > i'm new to perl and i want to know if perl has reflection like java? ... > how can i acces reflection and how powerfull is the reflection in perl? ... my $class = shift(); ... sub print { ...
    (perl.beginners)
  • Re: Passing "class" objects to a function
    ... Inside a sub, shift without a parameter will shift @_. ... A beginner in Perl "should" be explicit when they program...it may be redundant, but with the current pricing of disks, those few extra bytes won't hurt and it helps them remember what the defaults are. ... Maybe there should be a separation between "what Perl programming practices you would suggest to a beginner" and "what you do yourself"... ...
    (perl.beginners)
  • Re: New cross-language web development framework called Jasper
    ... languages, Perl amongst them. ... Jasper, and hopefully provide some helpful comments. ... my $arr = shift; ... sub keyExistsAndNonEmpty ...
    (comp.lang.perl.misc)