in reply to writing to log file

Sun751 given that this is your 40th SOPW question, I think it is time to push you a bit. Learning that you discover for yourself will stick with you in a way that no other kind of learning can.

You seem to have an idea of how to do each part of the program you want, so I'm guessing that the real question here is: "how do I structure a larger program so that it runs through several commands?" Instead of answering that question I'm going to throw a few quests back at you. I'd like to see what you come up with as a program once you have fulfilled these quests.

  1. Quest: write a short script that takes the content of $ARGV[0] and prints it out to a log file. If you aren't sure what $ARGV[0] is, search for @ARGV in perlvar. When this command is done, you should be able to type perl logit.pm ps and see the output of the ps command in your log file.
  2. Quest: rewrite your script so that $ARGV[0] is passed to a subroutine that takes a single parameter. Your entire script should look like this:
    use strict; use warnings; sub run_and_log { my ($cmd) = @_; #your code here } run_and_log($ARGV[0]);
  3. Quest: rewrite your subroutine so that it can take an array reference containing a list of commands. Your script should look something like this.
    use strict; use warnings; sub run_and_log { my $aCmds = $_[0]; # things to do before doing any command # hint - if you can do it for the first command and then # treat it as already done for each of the rest, it # belongs here - example: you only need to open the log # file once for the first command. All the rest of the # commands can reuse the LOG file handle foreach my $cmd (@$aCmds) { #things that need to be redone for each command } # things to do after all commands are done # hint: these are usually cleanup tasks: e.g. closing # file handles or printing the total number of successful # or unsuccessful commands } run_and_log(\@ARGV);
  4. Quest:. Rewrite your script so that $ARGV[0] contains the name of a file. This file stores a list of commands, one per line. The array reference passed to run_and_log stores lines read in from this file. For help on creating the array, look at How can I read in an entire file all at once.

If you have questions along the way, I strongly suggest you ask them on this thread. The same goes for when you complete each quest. If you post the results as a new node on this thread, we will be happy to give you feedback. We can give you much better help if we can see the context of your questions.

Also, try not to worry too much if you are using the fastest or most idiomatic or smartest way. For these quests the goal is to learn how to structure a program so that it does what you want.

Best and good luck, beth

Update: added additional quest (specify commands in a file rather than via the command line).

Update: fixed error in for loop of code skeleton for quest 3