Jeff Pan wrote:
> hi,

Hello,

> Is there a best way to find some lines which exists in both two files?

Your code logic says that you want to find lines in '2.txt' that are NOT in
'1.txt'.

> Someone has show me a method but it seems a little low efficiency.

Not only that but it doesn't work correctly.  If a line is not found in
'1.txt' then diff() will ALWAYS return 0.

> The code is as below:
> 
> open (T1,"1.txt") or die "$!";
> open (T2,"2.txt") or die "$!";
> 
> while(my $line=<T2>){
>   chomp $line;
>   print $line,"\n" unless diff($line);
> }
> 
> sub diff
> {
>    my $line=shift;
>    my $ok=0;
>    while(<T1>){
>        chomp;
>        if ($_ eq $line)
>        {
>            $ok=1;
>            last;
>        }
>    }
>    return $ok;
> }
> 
> close T2;
> close T1;

The usual way to do this is to use a hash:

open T1, '<', '1.txt' or die "open '1.txt' $!";
open T2, '<', '2.txt' or die "open '2.txt' $!";

my %hash;
while ( <T2> ) {
    $hash{ $_ }++
    }

while ( <T1> ) {
    print if exists $hash{ $_ }
    }

__END__



John
-- 
use Perl;
program
fulfillment

-- 
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