我在perl中创建了一个模块,但我不明白如何使用它

时间:2016-02-17 21:07:20

标签: perl module subroutine

所以这是我创建的模块:

#!/usr/bin/perl


use warnings;
use strict;
package Module1;

my @user;
my $count = 0;
my @test;
my @last =qx(last);
my @logins;
my %logins_by_user;
my @UserDiskUsage;
#my $pass =qx(sudo passwd -S @user);

#Opens the file /etc/passwd and puts the users with an uid over 1000 but less that 65000 into an array.
sub userloggins {
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;

#Counts how many times each user has logged in and stores them in a hash, then sorts them

for my $user (@user) {
$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 }     @user 
) {
print("$user: $logins_by_user{$user}\n");
}
}
userloggins(); 
#del 2, monitor user password age
print "-------------------------------------------------------\n";

PasswordAge();

sub PasswordAge {
my $days = 10;
my $currentdate = (qx(date +%s)) / 86400;
for my $i (0...$#user) {
    my @shadowDays = qx(sudo grep $user[$i] /etc/shadow | cut -d: -f3);
    if ($shadowDays[0] < ($currentdate - $days)){

        print ("User $user[$i] has not changed their password in $days days.\n");
    }
    #print "$currentdate\n";



    #print "$user Has not changed their password since $splitpass\n"; 
}
}

我想要发送数据的子程序叫做PasswordAge。我希望通过用户输入从另一个脚本发送数据的变量称为$ days。我怎样才能做到这一点 ?我试过在线寻找答案,但我不知道如何在我的案例中做到这一点。希望你明白。

1 个答案:

答案 0 :(得分:3)

问题的答案是:

  • 将模块保存为“Module1.pm”。
  • use Module1;
  • 在您的脚本中:Module1::PasswordAge();

然而,听起来有点光顾的风险 - 它可能值得阅读,例如perlmod作为创建模块的过程 - 虽然不是大规模困难,但在理解如何导入和加载模块之前,这有点不寻常。