cliftonsmithhp has asked for the wisdom of the Perl Monks concerning the following question:

I am using the following Perl script to determine the last logon of all users in /etc/passwd. I am VERY new to Perl, and I need to limit the search, however, to users that have a similar word (string) in their home directory. I am more POSIX shell savvy, but this is what I kinda am looking for: grep (string) /etc/passwd Using this file, is there somewhere I could grep for this (string) instead of sourcing in the entire /etc/passwd file?
#!/usr/local/bin/perl # Show last logins for every user in /etc/passwd # open(LASTLOGIN,"last|") || die "Cannot run 'last' command\n"; while (<LASTLOGIN>) { next if $_ eq ""; if (/^wtmp begin/) {$begin=$_ ; next}; ($name,$tty,$date)=/(\S+)\s+(\S+)\s+(\S+\s+\S+\s+\S+)/; $user{$name}=$date unless $user{$name}; } print $begin; close(LASTLOGIN); open(PASSWD,"/etc/passwd") || die "Cannot open '/etc/passwd'\n"; while (<PASSWD>) { next if /^\+/; ($name,$rest)=split(":"); $user{$name}="**No Logon Since /etc/wtmp File Created**" unless $user{ +$name}; } foreach $name (sort keys(%user)) { printf "%-10s %s\n",$name,$user{$name}; }

2004-10-19 Edited by Arunbear: Changed title from 'Easy one for the Monks !'

Replies are listed 'Best First'.
Re: Reporting last login according to wtmp for selected users
by jdporter (Paladin) on Oct 18, 2004 at 19:18 UTC
    (untested)
    #!/usr/local/bin/perl # # Show last logins for every user in /etc/passwd use strict; use warnings; # only report on users with this in their home dir path: my $special = 'foo'; my %user; my $begin; open LASTLOGIN, "last |" or die "Error runing 'last' - $!\n"; while (<LASTLOGIN>) { next unless /\S/; if ( /^wtmp begin/ ) { $begin = $_; } else { my($name,$tty,@date) = split; $user{$name} ||= "@date[0..3]"; # include time of login too. } } close LASTLOGIN; print $begin; open PASSWD, "/etc/passwd" or die "Error opening /etc/passwd for read +- $!\n"; while (<PASSWD>) { my($name,$homedir) = (split ':')[0,4]; $user{$name} ||= "**No Logon Since /etc/wtmp File Created**"; $homedir =~ /$special/ or delete $user{$name}; } close PASSWD; foreach my $name ( sort keys %user ) { printf "%-10s %s\n", $name, $user{$name}; }
Re: Reporting last login according to wtmp for selected users
by gellyfish (Monsignor) on Oct 19, 2004 at 09:15 UTC

    You may want to take a look at my module Sys::Lastlog - this includes an example program plastlog that may do what you want.

    /J\

wanted: meaningful node titles
by rjbs (Pilgrim) on Oct 19, 2004 at 14:29 UTC
    The title of this node is pretty miserable. Please try to use node titles that give some idea of what the content will be.
    rjbs