in reply to Make array from field of another array
Update: With your updated node, I can provide some more useful suggestions. You can accomplish your mapping using the code posted in Limbic~Region's subthread, so the smallest mod to your script the produces your desired result might look like:
#!/usr/bin/perl -w #<UnusedGrp.pl> Find unused Groups in /etc/group my $GROUPfile="/etc/group"; my $gfpid = open(GFILE, "<$GROUPfile") or die "$GROUPfile File Not Fou +nd: $!\n"; my $PASSWD="/etc/passwd"; my $pfpid = open(PFILE, "<$PASSWD") or die "$PASSWD File Not Found: $! +\n"; @PWLINES = <PFILE>; while (my $line = <GFILE>) { @GRP = split(/:/, $line); if (length($GRP[3]) < 2){ print "$GRP[0]:$GRP[2] is zero length\n"; my @GIDs = map { (split /:/)[3] } @PWLINES; my $seen = 0; for my $GID (@GIDs) { if ($GID == $GRP[2]) { $seen = 1 } } if (not $seen) { print "$GRP[0]:$GRP[2] has no users\n"; } } }
However, I would approach this problem a little differently. Given that you want to repeatedly check against the presence of a foreign key, the best approach here is Perl is usually using a hash. I would also use next for Loop Control rather than nested conditionals. My solution would look more like:
#!/usr/bin/perl -w #<UnusedGrp.pl> Find unused Groups in /etc/group use strict; my $GROUPfile="/etc/group"; my $gfpid = open(GFILE, "<", $GROUPfile) or die "$GROUPfile Open faile +d: $!\n"; my $PASSWD="/etc/passwd"; my $pfpid = open(PFILE, "<", $PASSWD) or die "$PASSWD Open failed: $!\ +n"; my %gids; while (my $line = <PFILE>) { my @user = split /:/, $line; $gids{$user[3]}++; } while (my $line = <GFILE>) { my @GRP = split(/:/, $line); if (length $GRP[3] > 1) { # $GRP[0]:$GRP[2] is not zero length next; } if ($gids{$GRP[2]}) { # GID found in passwd next; } print "$GRP[0] has no users and no GID references\n" }
though my final solution would probably be
#!/usr/bin/perl -w #<UnusedGrp.pl> Find unused Groups in /etc/group use strict; my $GROUPfile="/etc/group"; my $PASSWD="/etc/passwd"; open my $gh, "<", $GROUPfile or die "$GROUPfile Open failed: $!\n"; open my $ph , "<", $PASSWD or die "$PASSWD Open failed: $!\n"; my %gids = map { (split /:/)[3] => 1 } <$ph>; while (<$gh>) { my @fields = split /:/; next if length $fields[3] > 1; next if $gids{$fields[2]}; print "$fields[0] has no users and no GID references\n" }
I'll be happy to go over any questions you have about the above code. In particular, see Use strict warnings and diagnostics or die (or The strictures, according to Seuss).
|
|---|