-1

到目前为止,我有这个代码:

#!/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;

但现在我不知道下一步该做什么。我当时的理性是将 /etc/passwd 文件中的 7 个值拆分为匹配项,以查看有多少 $lastnames 有 5-10 个匹配项,但是我不知道与它们关联的 $username 是什么。

对于我的最终输出,我需要一个由 5-10 人共享的姓氏列表,因此示例输出将类似于:

史密斯:约翰·萨曼莎·贾里德57 dragonx349 6tron39

4

1 回答 1

1
#!/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} });
}
于 2014-06-12T23:57:20.183 回答