Process Management
- Here's one way to do it:
if (`date` =~ /^S/) { print "Go play!\n"; } else { print "Get to work!\n"; }
It just so happens that the first output character of the date command is an
Sonly on the weekend (SatorSun), which makes this program trivial. We invoke date, then use a regular expression to see if the first character is anS. Based on that, we print one message or the other. - Here's one way to do it:
open(PW,"/etc/passwd"); while (<PW>) { chomp; ($user,$gcos) = (split /:/)[0,4]; ($real) = split(/,/, $gcos); $real{$user} = $real; } close(PW); open(WHO,"who|") || die "cannot open who pipe"; while (<WHO>) { ($login, $rest) = /^(\S+)\s+(.*)/; $login = $real{$login} if $real{$login}; printf "%-30s %s\n",$login,$rest; }The first loop creates a hash
%realthat has login names for keys and the corresponding real names as values. This hash is used in the following loop to change the login name into a real name.The second loop scans through the output resulting from opening the who command as a filehandle. Each line of who's output is broken apart using a regular expression match in a list context. The first word of the line (the login name) is replaced with the real name from the hash, but only if it exists. When that's all done, a nice
printfputs the result ontoSTDOUT.You can replace the filehandle
openand the beginning of the loop with justforeach $_ (`who`) {
to accomplish the same result. The only difference is that the version with the filehandle can begin operating as soon as who starts spitting out characters, while the version with
whoin backquotes must wait for who to finish. - Here's one way to do it:
open(PW,"/etc/passwd"); while (<PW>) { chomp; ($user,$gcos) = (split /:/)[0,4]; ($real) = split(/,/, $gcos); $real{$user} = $real; } close(PW); open(LPR,"|lpr") || die "cannot open LPR pipe"; open(WHO,"who|") || die "cannot open who pipe"; while (<WHO>) { # or replace previous two lines with: foreach $_ (`who`) { ($login, $rest) = /^(\S+)\s+(.*)/; $login = $real{$login} if $real{$login}; printf LPR "%-30s %s\n",$login,$rest; }The difference between this program and the program from the previous exercise is that we've added an
LPRfilehandle opened onto an lpr process, and modified theprintfstatement to send the data there instead ofSTDOUT. - Here's one way to do it:
sub mkdir { !system "/bin/mkdir", @_; }Here, the mkdir command is given the arguments directly from the arguments to the subroutine. The return value must be logically negated, however, because a nonzero exit status from
systemmust translate into a false value for the Perl caller. - Here's one way to do it:
sub mkdir { my($dir, $mode) = @_; (!system "/bin/mkdir", $dir) && chmod($mode, $dir); }First, the arguments to this routine are named as
$dirand$mode. Next, we invoke mkdir on the directory named by$dir. If that succeeds, thechmodoperator gives the proper mode to the directory.