in reply to "Pattern Matching", not using regex

Dr. J

I started writing this up earlier today, but I had to leave it to do some work. When I came back to post I saw that Abigail had already posted a solution. This solution may not be as fast as her's but it is cut and paste-able. If you want to use it feel free

I also tried to make it simple as possible.

Thanks,
Kristofer

#!/bin/perl -w use diagnostics; use strict; use warnings; ############################################################ sub getAllLinesFromAFileandReturnItAsAnArray($) { my ($FILE) = $_[0]; #Redundant check. This code should be unreachable just by #the way I defined this sub '($)'. I do manual checking #of each varible as an anal principle. Just my style - Kristofer if (!defined($FILE)) { die ("I did not receive a filename"); } open my $FileDescripter => $FILE or die "Could not open '$FILE'\n"; my @ListOfStringsToReturn = <$FileDescripter>; close $FileDescripter; chomp @ListOfStringsToReturn; # my @ListOfStringsToReturn = (); # open (FileDescripter, "$FILE"); # while (<FileDescripter>) # { # if (defined($_)) # { # chop; # push @ListOfStringsToReturn, $_; # } # } # close(FileDescripter); return @ListOfStringsToReturn; } #=========================================================== my $FirstFile = "FileOne.txt"; my $SecondFile = "FileThree.txt"; my @FileOne = getAllLinesFromAFileandReturnItAsAnArray($FirstFile); my @FileTwo = getAllLinesFromAFileandReturnItAsAnArray($SecondFile); for (my $i = 0; $i < @FileOne; $i++) { print "Comparing Line $i in $FirstFile ... "; my $test = undef; for (my $j = 0; $j < @FileTwo; $j++) { if ($FileOne[$i] eq $FileTwo[$j]) { print " matched to line $j in $SecondFile\n"; print " FileOne: '$FileOne[$i]'\n"; print " FileTwo: '$FileTwo[$j]'\n"; #Setting j to @FileTwo will kill this loop $j = @FileTwo; $test = 0; } } if (!defined($test)) { print " not matched. Compared to $#FileTwo entries\n"; } }
Update based on Abigail's suggestion. Thanks Abigail for the lesson in Perl.

Replies are listed 'Best First'.
Re: "Pattern Matching", not using regex
by Abigail-II (Bishop) on Jul 22, 2002 at 17:17 UTC
    Please, please, please. Reading in all lines of a file into an array is standard idiom. Do not use such a silly, inefficient, routine. And NEVER EVER forget to check the return value of open.

    Here's how you read the file into an array:

    open my $fh => $file or die "Open failed: $!"; my @array = <$fh>; close $fh;
    If you want to chomp of newlines, add the following line:
    chomp @array;
    Don't reinvent the wheel. And don't code perl primitives in Perl.

    Abigail