in reply to Regular Expression

while (my $words = <DICT>) { chomp $words; push @matches, $words if $words =~ /a$/ }
or just  my @matches = grep { chomp; /a$/ } <DICT>;

Update: With CountZero's caveat, the second example will work fine on windows. That is Perl's internal grep, not the unix system utility of the same name. Perl chomp removes whatever $/ is from the end of a string - by default that is the native newline.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: Regular Expression
by CountZero (Bishop) on May 18, 2003 at 07:20 UTC

    The grep solution slurps the whole dictionary file as one list and can make for a huge process if the dictionary is large.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Re: Regular Expression
by optikool (Novice) on May 18, 2003 at 21:54 UTC
    Thanks for the information Zaxo. The first example cuts down a lot of code I had plan to use. I can't really use the second example because I need this to work on both windows and unix, though eventually it will be unix only. However the words are still missing when the search is started. Here is the code...
    use strict; use warnings; my @matches = (); open (DICT, "dictionary.txt") or die "Dictionary.txt: $!\n"; while (my $words = <DICT>) { chomp $words; push @matches, $words . " 1" if $words =~ /a$/; push @matches, $words . " 2" if $words =~ /.*[i].*[i].*[i].*[i].*[ +i].*/gi; push @matches, $words . " 3" if $words =~ /[^aeiou]/gi; my $reverse = reverse($words); push @matches, $words . " 4" if $words eq $reverse; } close (DICT); foreach (@matches) { print $_; }
      Regarding this issue:

      I need this to work on both windows and unix

      The safest way to remove line terminations across platforms is:

      s/[\r\n]+//;
      For that matter, you could probably just do s/\s+//g; based on the assumption that the only white space to be found in your dictionary file is the line breaks.
      You might want to check to see if the words are there inside of the while loop. A simple print statement like
      print "----$words-----\n";
      inserted after the chomp statement may detect the problem.