Perl Programming... Write a program that changes to some particular (hardcoded)
ID: 3847054 • Letter: P
Question
Perl Programming...
Write a program that changes to some particular (hardcoded) directory, like the system’s root directory, then executes the ls -l command to get a long-format directory listing in that directory. (If you use a non-Unix system, use your own system’s command to get a detailed directory listing.
Modify the previous program to send the output of the command to a file called ls.out in the current directory. The error output should go to a file called ls.err. (You don’t need to do anything special about the fact that either of these files may end up being empty.
Write a program to parse the output of the date command to determine the current day of the week. If the day of the week is a weekday, print get to work; otherwise, print go play. The output of the date command begins with Mon on a Monday. If you don’t have a date command on your non-Unix system, make a fake little program that simply prints a string like date might print. We’ll even give you this two-line program if you promise not to ask us how it works:#!/usr/bin/perlprint localtime( ) . " ";
(Unix only) Write an infinite loop program that catches signals and reports which signal it caught and how many times it has seen that signal before. Exit if you catch the INT signal. If you can use the command-line kill, you can send signals like so:$ kill -USR1 12345If you can’t use the command-line kill, write another program to send signals to it. You might be able to get away with a Perl one-liner:$ perl -e 'kill HUP = 12345'>
Explanation / Answer
Study the comments. Most of the code is self explanatory(its perl! :D)
use strict;
use warnings;
# Go to /home/<username>
chdir $ENV{'HOME'};
# Execute ls -l
my $result = `ls -l`;
# Incase of failure.
if ($? == -1) {
my $msg = "ls failed!" + $!;
# print $msg;
# Open for error.
open(my $err, '>', 'ls.err');
# Print stuff to error file.
print $err $msg;
close $err;
}
else {
# print $result;
# Open for output.
open(my $out, '>', 'ls.out');
# Print stuff to output file.
print $out $result;
close $out;
}
# Date stuff
$result = `date`;
$result =~ /(w{3}).*/;
# Sun and Sat start with an 'S', no other days do!!
if ($1 =~ /^S/) {
print "Go Play! ";
} else {
print "Work!! ";
}
Cheers,
PH
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.