我不确定您期望什么输出,也不确定我的代码是否符合您的要求,但以下代码首先查找出现在某人全名(部分)中的用户名。然后它会显示某个全名中出现的用户名。我知道这是一个丑陋的代码,可能不是最有效的解决方案,但请告诉我这是否是您预期的输出。
#!/usr/bin/perl
use strict;
use warnings;
open PASSWD, "/etc/passwd" or die "$!";
my @usernames;
my @fullnames;
while (<PASSWD>) {
chomp;
# First entry is username, 5th entry is full name if exists.
push @usernames, (split ":", $_)[0];
my $fullname = (split ":", $_)[4];
push @fullnames, $fullname if $fullname ne "";
}
my %found_usernames;
foreach my $username (@usernames) {
foreach my $fullname (@fullnames) {
if ($fullname =~ m/$username/i) {
# Push to the array if full name was already found before.
# Otherwise, create an anonymous array
if (defined $found_usernames{$fullname}) {
push $found_usernames{$fullname}, $username
}
else {
$found_usernames{$fullname} = [$username];
}
}
}
}
# Print
foreach my $key (keys %found_usernames) {
print "Users: ", join(",", @{$found_usernames{$key}}), " appear in fullname $key\n";
}
close PASSWD;