On Sun, Mar 05, 2006 at 07:24:05AM -0800, Scott Ulmen wrote:

> There must be a better (read shorter) way to do what I did.  In the  
> "teach yourself perl" book (I'm trying to learn) there is an activity  
> as follows:
> 
> Write a short program that does the following:
> -Opens a file
> -Reads all the lines into an array
> -Extracts all the words from each line
> -Finds al words that have at least four consecutive consonants (ex:  
> thoughts or yardstick)
> 
> My solution is:
> 
> #!/usr/bin/perl -w
> 
> open(LINES, "act6") || die "Can't open the file act6: $!";
> @lines=<LINES>;
> close(LINES);
> 
> foreach $singleline (@lines) {
>       chomp $singleline;
>       @words=split(/ /, $singleline);
>               foreach $singleword (@words) {
>                       $singleword=~s/\.//;
>                       if ($singleword=~m/[^aeiou]{4,}/i) {
>                               print "One of the words is: $singleword\n";
>                       }
>               }
> }
> 
> 
> With the file "act6" containing only the following 3 lines:
> 
> This is a test file.
> There are only two words that meet the match.
> Those words are thoughts and yardstick.
> 
> The above works, but it sure seems like a lot of effort to simply  
> pull the individual words out of each line!

I suppose it depends on your goals.  Your code is quite readable and
reasonably concise.  It would need to be much longer in many comman
languages.

However, if you are happy with your definitions of words and consonants,
and don't mind not reading the whole file into memory (which is usually
a better idea anyway) the following probably does about the same thing
as your code:

  perl -lane's/\.//,/[^aeiou]{4,}/i&&print [EMAIL PROTECTED]' act6

For anything you might want to use more than once your code is probably
better.  You might want to consider adding "use strict;" at the top of
the program and fixing the problems it throws up my sprinkling "my"
around your code as required.  Personally I would probably remove the
word "single" from the code and check the close() worked.

In fact, I suppose I'd probably write something similar to:

#!/usr/bin/perl

use warnings;
use strict;

open my $fh, "<", "act6" or die "Can't open file act6: $!";

while (<$fh>)
{
    for my $word (split)
    {
        $word =~ s/\.//;
        print "One of the words is: $word\n"
            if $word =~ /[^aeiou]{4,}/i;
    }
}

close $fh or die "Can't close file act6: $!";

Which isn't a million miles from what you wrote.

-- 
Paul Johnson - [EMAIL PROTECTED]
http://www.pjcj.net

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to