LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   perl script to rationalize /etc/groups (https://www.linuxquestions.org/questions/programming-9/perl-script-to-rationalize-etc-groups-4175467070/)

scottmusician 06-23-2013 07:33 AM

perl script to rationalize /etc/groups
 
Hi all,

I am trying to write a simple perl script to optimize my /etc/groups, to make sure that it doesn't contain any members that don't have corresponding /etc/passwd entries.

here's what I have so far, but it all seems a little cumbersome:
Code:

#!/usr/local/bin/perl

open(F, "/etc/passwd");
@passwd = <F>;
chop(@passwd);
open(F, "/etc/group");
@group = <F>;
chop(@group);

for ($i=0; $i<$#group; $i++) {
        $line = $group[$i];
        $line =~ /^(..*):(..*):(..*):(..*)$/;
        ($group, undef, undef, $members) = ($1, $2, $3, $4);
        @members = split(/,/, $members);
        foreach $m (@members) {
                printf("%s\n", $m) unless grep(/^$m:/, @passwd);
        }
}

Is there a neater way of doing this in perl?

(PS: it needs to be in perl, as it's also for my programming class :) )

pan64 06-23-2013 09:25 AM

yes, you can try to use a hash:
store all the usernames in a hash, %users (values are not important, we need to keys only).
and you can write your search as: grep (! exists $users{$_}, split(/,/, $members));
Not tested, there can be other possibilities, for example using map.

chrism01 06-25-2013 02:05 AM

1. always use -w & strict
Code:

#!/usr/bin/perl -w
use strict;

2. use 3 arg open and always close files you've opened asap (especially key ones like passwd!) and check open/close worked ok
Code:

open(KFILE, "<", "kfile.txt" ) or die "Can't open kfile: $!\n";
@passwd = <F>;
chomp(@passwd);
close(KFILE) or die "Can't close kfile: $!\n";

& prefer chomp() to chop().

http://perldoc.perl.org/
http://www.perlmonks.org/?node=Tutorials
http://www.tizag.com/perlT/index.php


All times are GMT -5. The time now is 03:42 PM.