[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] 4 Consecutive Letters



On Mon, Aug 14, 2000 at 11:04:16AM -0500, Greg Bacon wrote:
> In message <20000814095836.A595478@linguist.dartmouth.edu>,
>     Ronald J Kimball writes:
> 
> : Here's my first solution:
> : 
> :   perl -ne'@a=a..z;for$i(0..22){print,last if/@{[$a[$i]..$a[$i+3]]}/x}'
> : 
> : And a slightly shorter one:
> : 
> :   perl -ne'for$i(97..119){print,last if/@{[map chr,$i..$i+3]}/x}'
> 
> I'll probably lose my tour card, but
> 
>     sub inarow {
>         my $word = lc(shift || '');
>         my $cnt  = shift || 0;
> 
>         return unless $word && $cnt > 0;
>         return unless length($word) >= $cnt;
> 
>         return 1 if $cnt == 1;

Good, factor out the obvious cases first!


>         my $code = q<
>     do {
>         study $word;

You study $word, but your target string for the matches is $a.


>         my $a = "abcdefghijklmnopqrstuvwxyz";
>         if (>;

That threw me for a second before I realized it was the end of the q<>
string!  :)


>         $code .= join ' || ',
>                  map '$a =~ /' . $_ . '/',
>                  map substr($word, $_, $cnt),
>                  0 .. length($word)-$cnt;

Two maps are no better than one:

map {'$a =~ /' . substr($word, $_, $cnt) . '/'} (0 .. length($word)-$cnt);


Using a constant string for the target and the input for the regex is a
neat idea.  In this case it means a lot of evalling, though...


A bigger concern is the evalling of external data; as production code this
would need some good taint-checking, in case the data file contains a line
like: @{[`rm -rf *`]}


>         $code .= q<) { 1 }
>         else { 0 }
>     }>;

I don't think you need the if/else; C<if (expr) then { 1 } else { 0 }> is
equivalent to C<scalar(expr)>.


>         #print $code, "\n";
>         my $result = eval $code;
>         die $@ if $@;
> 
>         $result;
>     }


Ronald

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe