16.1. Write a program that changes the time zone by using the TZ environment variable
then uses exec to run the date command. Get the valid time zones from your system.
use 5.016; $ENV{TZ} = 'Iran'; exec 'date';
16.2. Use the backticks operator to read the output of ls –l command then report which
users and groups it finds. Run it in the directory that contains the user home directories.
use 5.016; use autodie; chdir '/'; my (%group,%user); foreach (`ls -l`) { next if /^total/ ; my (undef,undef,$user,$group) = split; $user{$user}++; $group{$group}++; } foreach my $user (sort keys %user) { printf "%-8s %3d\n",$user,$user{$user}; } foreach my $group (sort keys %group) { printf "%-8s %3d\n",$group,$group{$group} ; }
16.3. Rewrite the program from the previous exercise, but use IPC::System::Simple
instead of backticks.
use 5.016; use autodie; use IPC::System::Simple qw(capturex); chdir '/'; my (%group,%user); foreach (capturex('ls','-l')) { next if /^total/ ; my (undef,undef,$user,$group) = split; $user{$user}++; $group{$group}++; } foreach my $user (sort keys %user) { printf "%-8s %3d\n",$user,$user{$user}; } foreach my $group (sort keys %group) { printf "%-8s %3d\n",$group,$group{$group} ; }
16.4. Write a program to print all of the environment variables, in alphabetical order,
along with their values. Can you turn this into a CGI program?
use 5.016; use autodie; print "Content-type: text/plain\n\n"; foreach my $key (sort %ENV) { printf "%-30s %s\n",$key,$ENV{$key}; }
16.5. Modify your program from Exercise 16.1 to remove the value from PATH environment
variable. What other changes do you have to make as a result?
use 5.016; use autodie; $ENV{PATH}=''; $ENV{TZ} ='US/Pacific'; exec '/bin/date';
16.6. Modify your answer to Exercise 16.2 to execute the command using open and a
pipe. Read the input one line at a time through a filehandle and report the same results.
use 5.016; use autodie; open my $ls,'-|','ls','-l'; my (%group,%user); while (<$ls>) { next if /^total/ ; my (undef,undef,$user,$group) = split; $user{$user}++; $group{$group}++; } foreach my $user (sort keys %user) { printf "%-8s %3d\n",$user,$user{$user}; } foreach my $group (sort keys %group) { printf "%-8s %3d\n",$group,$group{$group} ; }
16.7. Write a program that reads in lines of input and counts the number of lines with
of e’s in them. Use your program from Exercise 16.4 as the source of input.
use 5.016; use autodie; open my $en ,'-|',$^X,'sex16-4.pl'; my $sum; while (<$en>) { next unless /e/ ; $sum++; } say "The numberof lines with an 'e' is $sum";
16.8. Use the Windows title command to create a “progress bar” in the title bar of the
cmd or command window. Add a * character once every second for a minute.
use 5.016; use autodie; foreach ( 1 .. 60) { system 'title', '*' x $_; sleep 1; }