http://www.perlmonks.org?node_id=617055


in reply to Re: finding number of contiguous letters
in thread finding number of contiguous letters

Far better solutions have been presented, but here is another. I was considering how to do if we had tail recursion. I had been hoping to place all code in the argument list...

sub parts { my ( $cnt, $ra_out, $ra_val, $ra_in ) = @_; if( $#$ra_val != $cnt ){ #working array not full if( $#$ra_in > -1 ){ #fill it up push(@$ra_val, shift(@$ra_in)); parts( $cnt, $ra_out, $ra_val, $ra_in ); } else { #done with list return; } } else { push(@$ra_out, join('',@$ra_val)); #add to outp +ut array, joined ltr string shift(@$ra_val); #rip off fir +st ltr push(@$ra_val, shift(@$ra_in)) if($#$ra_in > -1); #add new ltr +, if any remaining parts( $cnt, $ra_out, $ra_val, $ra_in ); } } my @in = split( '', "computer" ); # input array of individual letters my @out; # out array of strings each of $cnt ++1 ltrs my @val; # working array of individual lette +rs, $cnt+1 elements parts( 2, \@out, \@val, \@in ); #results in @out

..Otto

Replies are listed 'Best First'.
Re^3: finding number of contiguous letters
by blazar (Canon) on May 23, 2007 at 20:03 UTC
    I was considering how to do if we had tail recursion.

    We do have tail recursion. Well not really: sort of. That's courtesy of magic goto: but then of course one has to explicitly make use of it, not that TR is automatically recognized, which is what you clearly meant.

      Blazar,

      You got me thinking, I'm going to play with this some more, but first... are sub arguments, ie a list, evaluated in order?

      For example suppose a list is composed of ( <a>, <b>, <c> )where each of the a, b, c are one or more sub calls that may mutate some value, which may be used by others further down the list, will the list values be evaluated in order of a, b, c, or is it undefined?

      I quickly looked at the sub function and the comma operator which did not shed any light, or at least I didn't see it...

      .. Otto

        For example suppose a list is composed of ( <a>, <b>, <c> ) where each of the a, b, c are one or more sub calls that may mutate some value, which may be used by others further down the list, will the list values be evaluated in order of a, b, c, or is it undefined?

        IIUC, why don't you find out yourself?

        #!/usr/bin/perl -l use strict; use warnings; BEGIN { my $foo; sub foo () { $foo } for my $n (qw/a b c d e f/) { no strict 'refs'; *$n = sub () { warn $n; $foo++ }; } } my $arr=(a,b,c,d,e,f); print foo, $arr; __END__