Tuesday, August 28, 2007

Using system and exec (Part 9)-- Perl Study Notes

Using system and exec (Part 9)-- Perl Study Notes

Execute command shelll

  Using system commad

     
    the function system to invoke the shell command and return the exist code until the  shell command finished
         #example of system command usage
         #example 1
         #execute the date and output the result to the file right_now.
         #output one message and exit if the command fails
           system("date >right_now") && die "cannot create right_now";

         #example 2
         $where = "who_out.".++$i;
         #command followed $ like below, the shell will return without waiting
         # for the command finished.   
         # in below case, the return value is true if the command is executed or
         # false if the command is not invoked successfully.
         system "(date) >$where

    system can also receive command arguments, for example
         #example
        @args1=qw(perl.exe C:\clearquest\MultiScript\cq_exportol_zl.pl)
    system(@args1)==0 || die "system @args failed: $?"

        
    system can run multiple command and separated with comma, but the return value is not the exit code of each command but the successful or not indicator of invoking the command


Using backslash

         #example 1
         # get each output line of the command dir in each iternation
        foreach (`dir`)   
         {
            chomp();  
                   #get only file lists and exclude the folder
            unless (/<DIR>/) 
            {
                       ($modify_date,$modify_time,$amorpm,$filename)=/(\S+)\s+(\S+)\s(\S+)\s+\S+\s+(.*)/;
           print "$filename is created at $modify_date $modify_time $amorpm";
                     }
            }
          

  Using filehandles
       #example 1
       # to get the result to print the line which contains zhengol
       open (COMMANDOUTPUT, "dir|");
       foreach (<COMMANDOUTPUT>)
          {
               #print the user containing zhengol
               print if (/DIR/);
          }
       close (COMMANDOUTPUT);

        #example 2
        #to print the message to the printer
        open(COMMANDINPUT, "|lpr -Pslatewriter");
        print COMMANDINPUT, "Testing Message";
        close(COMMANDOUTPUT) ;
 
  Using folk/exec/wait/waitpid
     fork to clone current process to run    
     #example 1

    if (!defined($kidpid = fork())) {
       # fork returned undef, so failed
        die "cannot fork: $!";
    } elsif ($kidpid == 0) {
        # fork returned 0, so this branch is the child
        exec("date");
        # if the exec fails, fall through to the next statement
         die "can't exec date: $!";
    } else {
        # fork returned neither 0 nor undef,
        # so this branch is the parent
        waitpid($kidpid, 0);
    }

No comments: