I’m new to perl and was wondering if I can get some help. I have a project and I got this code to work…was wondering if anyone can take a look at it for me.
the project calls for these items
- get user input,
- accept command line arguments,
- read and parse a data file,
- use lists, arrays or hashes,
- clean, parse and organize the information in a usable format,
- write the data to a file,
- use control structures and loops,
- include subroutines,
- use Regular Expressions and advanced string functions.
#!/bin/perl -w
$ARGVCHK = "N" ;
$ARGVUSER = "" ;
$DATE = `date "+%m/%d/%Y %H:%M:%S"` ;
chomp $DATE ;
#loop to check for cmd arg below -r <username> -a <username> -l <username>
while (@ARGV) {
if ( $ARGV[0] eq "-l" ) {
# -l list the users in twdb
$ARGVCHK = "L";
shift @ARGV;
}
# -a Adds a user to twdb from /etc/passwd (needs to chk if usr is already in twdb)
elsif ($ARGV[0] eq "-a") {
$ARGVCHK = "A";
shift @ARGV ;
if ( @ARGV) {
$ARGVUSER = $ARGV[0] ;
shift @ARGV;
}
else {
print "missing username\
";
exit (1);
}
}
# -r removes a users from twdb
elsif ($ARGV[0] eq "-r" ) {
$ARGVCHK = "R" ;
shift @ ARGV ;
if ( @ARGV ) {
$ARGVUSER = $ARGV[0] ;
shift @ARGV ;
}
else {
print " missing username\
" ;
exit (1) ;
}
}
else {
print "proj.pl [-l -a -r <username>]\
";
exit (0);
}
}
print " the arg chk is $ARGVCHK\
";
print "the user is $ARGVUSER\
";
if ( $ARGVCHK eq "R" ) { DELUSER() ; }
if ( $ARGVCHK eq "A" ) {ADDUSER() ; }
sub DELUSER { # start sub
$IFEXIST = "N" ;
open (TW, "project.users" );
open (LOG, ">>audit.log" );
while ( $tw = <TW> ) {
@dbline = split (":" , $tw);
if ( $dbline[0] eq $ARGVUSER ) {
$IFEXIST = "Y" ;
} else {
push ( @newtw , $tw ) ;
}
}
close TW ;
if ( $IFEXIST eq "Y" ) {
open (TW, ">project.users");
print TW @newtw ;
print LOG "$DATE deleted $ARGVUSER\
";
}
else {
print STDERR " This user is not in the db \
";
exit (3);
}
}
sub ADDUSER {
$process = `ps -u $ARGVUSER | wc -l`;
$process--;
chomp( $diskUsuage = `du -sk ` );
$diskUsuage = substr($diskUsuage, 0, 6);
print "This is the ADDUSER \
" ;
open ( TW , "project.users" ) ;
while ( $tw = <TW> ) {
@dbline = split (":" , $tw );
if ( $dbline[0] eq $ARGVUSER) {
print STDERR" This user is in the db \
";
exit (3);
}
}
close TW ;
open ( PWFILE , "/etc/passwd" ) ;
open ( TW, ">>project.users" );
open ( LOG, ">>audit.log" );
open ( PD, ">>process.users" );
while ( $line = <PWFILE> ) {
@pwl = split ( ":" , $line);
if ($pwl[0] eq $ARGVUSER ) {
print TW "$pwl[0]:$pwl[4]:$pwl[3]:$pwl[5]\
" ;
print LOG "$DATE added $pwl[0]\
";
print PD "$ARGVUSER:$process:$diskUsuage:$pwl[5]\
";
}
}
close (PWFILE);
close (TW);
close (LOG);
}