在perl中对变量进行排序

时间:2016-02-16 15:03:10

标签: perl sorting

以下是代码:

#!/usr/bin/perl

use warnings;
use strict;

my @user;
my $count = 0;
my @test;
my @last = qx(last);
my @logins;

# Opens the file /etc/passwd and puts the users with an uid
# over 1000 but less that 65000 into an array.
open( my $passwd, "<", "/etc/passwd") or die "/etc/passwd failed to open.\n";

while (my $lines = <$passwd>) {
    my @splitarray = split(/\:/, $lines );

    if( $splitarray[2] >= 1000 && $splitarray[2] < 65000) {
        $user[$count] = $splitarray[0];
        #print "$user[$count]\n";
        $count++;
    }
}
close $passwd;

for my $i (0 .. $#user) {
    my $counter = 0;
    @logins =qx(last $user[$i]);
    for my $j (0 .. $#logins) {
        if ($logins[$j] =~ /$user[$i]/) {
            $counter++;
        }
    }

    print $user[$i] . ":" . $counter . "\n";
}

这个输出看起来像这样:

user1:15
user2:3
user3:6
user4:2

我如何对此进行排序,以便向顶部显示登录次数最多的用户?我尝试了哈希,但似乎无法做到正确。由于它们不是数组,我不知道如何对它们进行排序。

2 个答案:

答案 0 :(得分:3)

您只有一个登录计数器。为了按登录计数对用户进行排序,您需要每个用户的登录计数。

my %logins_by_user;
for my $user (@users) {
   $logins_by_user{$user} = grep /^\Q$user\E /, `last '$user'`;
}

for my $user (
   sort { $logins_by_user{$b} <=> $logins_by_user{$a}  ||  $a cmp $b } @users
) {
    print("$user: $logins_by_user{$user}\n");
}

答案 1 :(得分:0)

这是一个使用哈希并打印按登录计数排序的用户的版本:

#!/usr/bin/env perl    

use strict;
use warnings;
use 5.010;

open(my $passwd, "<", "/etc/passwd") or die "/etc/passwd failed to open.\n";

my %login_count;
while (<$passwd>) {
  my @splitarray = split(/\:/);
  if ($splitarray[2] >= 1000 && $splitarray[2] < 65000) {
    my $user   = $splitarray[0];
    my @logins = qx(last $user);

    # Remove lines that don't mention the user name
    @logins = grep /$user/, @logins;

    # Using an array in scalar context returns the number of items in the array
    $login_count{$user} = @logins;
  }
}
close $passwd;

# List users sorted by login count
say "$_ : $login_count{$_}"
  for sort { $login_count{$a} cmp $login_count{$b} } keys %login_count;