A.13. Chapter 14

  1. 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 S only on the weekend (Sat or Sun), which makes this program trivial. We invoke date, then use a regular expression to see if the first character is an S. Based on that, we print one message or the other.

  2. 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 %real that 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 printf puts the result onto STDOUT.

    You can replace the filehandle open and the beginning of the loop with just

    foreach $_ (`who`) {

    to accomplish the same result. The only difference is that the version with the filehandle can begin operating ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.