How do I find all "last names" which are shared by 5-10 users in an /etc/passwd file?

120 Views Asked by At

So far I have this code:

#!/use/bin/perl -w

$filename = '/etc/passwd';

open(FILE, $filename) or die "Could not read from $filename, program halting.";
while (<FILE>) {
    chomp;
    ($username, $password, $uid, $gid, $uname, $home, $shell) = split(':', $_);
    my ($lastname, $firstname) = split(/ /, $uname, 2);
}

close FILE;

But now I am stuck with what to do next. My rational at the time was to split up the 7 values on the /etc/passwd file at do a match to see how many $lastnames had 5-10 matches, but then I would not know what the associated $username is with them.

For my final output I need to have a list of last names which are shared by 5-10 people so sample output would be something like:

smith : john samantha jared57 dragonx349 6tron39

1

There are 1 best solutions below

2
On
#!/usr/bin/perl

#always use strict. use warnings
use strict; 
use warnings;
use autodie;

my $filename = '/etc/passwd';

#use lexical file handle, don't need to explicitly close
#3 argument form of open.   `use autodie;` takes care of error checking.
open my $fh, '<', $filename;

#users will hold key value pairs. Key = lastname, Values: arrayref of usernames
my %users; 

while (<$fh>) {
    chomp;
    my ($username, $uname) = (split ':')[0, 4]; #Got rid of other data, not using it
    my $lastname = (split ' ', $uname)[0]; #Only need the lastname
    push @{ $users{$lastname} }, $username;
}

#Get keys of lastnames that are shared by 5 or more people
my @five_plus = grep { @{ $users{$_} } >= 5 } keys %users;

#So you can see the data
for my $key(@five_plus){
    print "$key:\n";
    print "\t$_\n" for(@{ $users{$key} });
}