http://www.perlmonks.org?node_id=902954

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

Greetings, it has been quite a while since I posted a question, but I've been lurking always reading the wisdom contained herein.

My question is this: I have 2 text files. Each one looks like something one would see when they cat /etc/passwd. The first file (I'll call it file1) has a list of users that need accounts. The second file has a list (in /etc/passwd format) of current accounts.

I easily created a list of users that *need* accounts by simple shell looping and grep. I was also able to produce a list of duplicate users easily enough via the shell again.

Alas, the last thing i wanted to do was to show who was left. These would be the accounts that have to be deleted. When simple shell one liners were of no avail, I turned to my swiss army knife of text processing, but I must admit that I am thwarted by this seemingly simple task.

Could I have just edited the files side by side? I could have, but I thought I was cheating myself out of an opportunity to learn something. And I here I am. I have code that I will paste below with copious comments as to what I think I should do, but what ultimately escapes me.

In my defense I will say one thing. I am not a programmer by trade, nor have I taken any programming courses outside of basic programming, and Pascal in high school.

#!/usr/bin/perl use strict; # Grep a user line OUT of a file, given a list of names, from another +file # psuedo code: # if file1 contains a name from file2, skip the line # if file1 does NOT contain a name from file2, print the line. # # I am using this to determine a list of # accounts that should be present, or not, on a server my @users; my $file1=$ARGV[0]; my $file2=$ARGV[1]; open FILE1, "<$file1" or die "Cannot open $file1: $!\n"; my @file1=<FILE1>; close FILE1; open FILE2, "<$file2" or die "Cannot open $file2: $!\n"; my @file2=<FILE2>; close FILE2; # Create @users array my @out; foreach my $line (@file2) { if ($line =~ /#/) { @out=split /\s+/,$line; push @users,$out[1]; } } LINE: foreach my $line (@file1) { USER: foreach my $user (@users) { print "is $user on $line"; if ($line =~ /$user/i) { print "YES $user is on $line ; next LINE\n"; next LINE; } else { # This is where I get into trouble. I'm thinking I need to set # some kind of flag or something, because otherwise I will exhau +st # the total list of users and will either get false positives # or skip them all together... print "nope... next USER\n"; next USER; } } }

Very funny Scotty... Now PLEASE beam down my PANTS!