tcf03 has asked for the wisdom of the Perl Monks concerning the following question:

I have two files

A contains multiple lines

userA, machine, last_logged_on userB, machine, last_logged_on

B contains multiple lines

UserA, password, location UserB, password, location

I want to open file A get the username

open (A, "FileA") || die "$!\n"; open (B, "FileB") || die "$!\n"; while (my @FILEA=<A>) { foreach my $line(@FILEA){ my ($nameA, $machine, $laston)=split(/,/,$line);

Here is where I want to have FileB opened and check $nameA against $nameB and if the match, do some stuff...

foreach my $lineb(@FILEB){ my ($NameB, $password, $location)=split(/,/,$lineb); if ( $nameA = $nameB ) { print "$nameA, $machine, $password\n"; }

It just doesnt seem to work like this...

Janitored by davido to clean up formatting.

Replies are listed 'Best First'.
Re: searching two files
by ikegami (Patriarch) on Dec 22, 2004 at 21:19 UTC

    First, you need to read up on how to read files. Second, when you want to your code to look something up -- you want to lookup if a name is in the other file -- think of hashes. The following should be useful.

    use strict; use warnings; my %fileA; my %fileB; my %users; # Read in FileA. open(A, "FileA") || die "$!\n"; while (<A>) { my ($name, $machine, $laston) = split(/,/, $_); $fileA{$name} = [ $machine, $laston ]; } close(A); # Read in FileB. open(B, "FileB") || die "$!\n"; while (<B>) { my ($name, $password, $location) = split(/,/, $_); $fileB{$name} = [ $password, $location ]; } close(B); # Check for users missing in FileB. # Merge records found in both FileA and FileB. foreach my $name (keys(%fileA)) { if (!exists($fileB{$name})) { warn("$name was found in file FileA, but not in file FileB.\n"); next; } $users{$name} = [ $fileA{$name}, $fileB{$name} ]; #delete($fileA{'name'}); # not needed delete($fileB{'name'}); } # Check for users missing in FileA. foreach my $name (keys(%fileB)) { if (!exists($fileA{$name})) { warn("$name was found in file FileB, but not in file FileA.\n"); } } # Do something with users. # Specifically, display matches. foreach my $name (sort keys(%users)) { printf("user %s\n". "machine: %s\n". "last on: %s\n". "password: %s\n". "location: %s\n". "\n", @{$users{$name}} ); }
Re: searching two files
by gopalr (Priest) on Dec 28, 2004 at 11:17 UTC

    Hi,

    Your comparison operator is wrong...

    You should have use the following:

    OPTION 1:
    if ( $nameA == $nameB ) { print "$nameA, $machine, $password\n"; }
    OPTION 2:
    if ( $nameA =~ m#^$nameB$#) { print "$nameA, $machine, $password\n"; }

    Regards,

    Gopal.R