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

OK again I have two files, scanned.txt and importtodb.csv. both contain data separated by commas and the first item on each list is a machine name,

first I want tofind the common machine names in both and then make a new file of comma delimited values made up of items from each. ie

fileA A,B,C,D fileB A,E,F,G,H New File (fileC) A,B,D,G
Here is the code I currently have and am having a hrd time getting past this point...
#!/usr/bin/perl use strict; use warnings; my %scanned=(); my %import=(); my @LIST=(); open(SCAN, "scan3.txt") || die "$!\n"; while (<SCAN>) { my ( $machine, $luser, $hacked, $privel, undef ) = split(/,/,$_); $scanned{$machine}=[ $luser, $hacked, $privel ]; } close (SCAN); open(IMPORT, "importtodb.csv") || die "$!\n"; while (<IMPORT>) { my ( $machine, $user, undef, undef, undef, undef, $locale, und +ef ) = split(/,/,$_); $import{$machine}=[ $user, $locale ]; } close (IMPORT); foreach my $machine (keys(%scanned)) { if(exists($scanned{$machine})) { push(@LIST, $machine); } } foreach my $item(@LIST){ print "$item\n"; }
The actual new file Ill need will contain
$machine,$luser,$user,$hacked,$locale

Replies are listed 'Best First'.
Re: reprise searching two files
by osunderdog (Deacon) on Dec 23, 2004 at 15:27 UTC

    One observation is that I don't think you need the %import hash. (In fact you aren't using it later in your script) You could append the items you find in the second file to the items you have already collected in the %import hash.

    while (<IMPORT>) { my ( $machine, $user, undef, undef, undef, undef, $locale, und +ef ) = split(/,/,$_); push(@{$scanned{$machine}}, $user, $locale); } close (IMPORT)
    Hope that helps.

    "Some days I feel like a Packled."


    OSUnderdog
I don't really understand the existing code but...
by tphyahoo (Vicar) on Dec 23, 2004 at 16:18 UTC
    I have had a similar problem and solved it using an array of hashes approach.

    I would solve your issue using three array of hashes.

    Write functions that get your two delimited files into an array of hashes. Something like:

    # Function that gets passwordLogins from a text file sub get_loginPasswords { my $filename = shift; my @loginPasswords; open F, "< $filename" or die "Cannot open logins file: $filename \n" +; while (<F>) { chomp; if ($_ =~ /\w+@\w+\.\w+,\w+/) { my ($login, $password); ( $login, $password ) = split( ',' ); my $Login = { login => $login, password => $password }; push @loginPasswords, $Login; } else { die "Error in login file format: $filename "; } } close F; return \@loginPasswords; }
    Then do something like follows
    for (%fileAArrayOfHashes) for (%fileBArrayOfHashes) if (file A column A matches file b column A) { add the columns you want to %hashC push (@fileCarrayOfHashes,\%hashC)
    Sorry, the above syntax may be wrong even where it's not pseudocode, but the general idea should work.

    Hope that helps!

    thomas.