in reply to Matching Text

Shorter, more idiomatic, and more efficient code attached. Feel free to modify. Output goes to STDOUT, which can be directed to a file.
#!/usr/bin/perl use strict; use warnings; @ARGV > 0 or die "Insufficient arguments: Need word file, and Dict fil +e names"; my ($wordfile, $dictfile) = @ARGV; open my $d, "<", $dictfile or die "Cannot open $dictfile: $!"; open my $w, "<", $wordfile or die "Cannot open $wordfile: $!"; my %dict = map {split /\s/,$_,2} <$d>; close $d; while (defined (my $line=<$w>)){ for (split /\s/,$line){ if (my $meaning = $dict{$_}){ print "$_: $meaning\n"; next; } print "$_ is not in the dictionary\n"; } } close $w;

             All great truths begin as blasphemies.
                   ― George Bernard Shaw, writer, Nobel laureate (1856-1950)

Replies are listed 'Best First'.
Re^2: Matching Text
by jwkrahn (Abbot) on Apr 03, 2012 at 05:11 UTC
    my %dict = map {split /\s/,$_,2} <$d>; close $d; while (defined (my $line=<$w>)){ for (split /\s/,$line){ if (my $meaning = $dict{$_}){ print "$_: $meaning\n"; next; } print "$_ is not in the dictionary\n"; } }

    I would write that as:

    my %dict = map split( ' ', $_, 2 ), <$d>; close $d; while ( <$w> ) { for my $word ( split ) { if ( exists $dict{ $word } ) { print "$word: $dict{ $word }"; next; } print "$word is not in the dictionary\n"; } }

    The use of /\s/ with split will screw up the dictionary if there are any leading whitespace.    (Anything that can go wrong, will go wrong. -- Murphy)

      agreed. (++). my split-fu is not the greatest.

                   All great truths begin as blasphemies.
                         ― George Bernard Shaw, writer, Nobel laureate (1856-1950)

      Hey guys thanks this seems to be working real well with printing to the screen. I just need to figure out how to get it to output to an external file

Re^2: Matching Text
by Chad C (Initiate) on Apr 09, 2012 at 23:09 UTC

    I can't seem to figure out how to get it to go from STDOUT to output to a file. It would need to be just the dictionary items not the items that aren't in the dictionary and printing to the terminal screen. Thanks again I appreciate all help!!

      Never mind realized I had to put it into the Unix command line and not change the script. Thanks again guys you saved me big time!!