Showing posts with label Perl. Show all posts
Showing posts with label Perl. Show all posts

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);
    }

Wednesday, August 8, 2007

Directory Access && File and Directory Manipulation (Part 8)-- Perl Study Notes

Directory Access && File and Directory Manipulation (Part 8)-- Perl Study Notes

 Change Directory Tree
  chdir($dirpath);
  #here is the example
  print "where do you want to go?"
  chomp($toPath=<STDIN>);
  if(chdir $where){
   # we got there
   }
   else
   {
   # we cannot go there
   }
 
 Globing
  <$pattern>; #In array context, it returns all files, the folder as well, matched the pattern. In scalar context, it returns the next file name it matched the pattern

  glob($pattern); #it is equivalent to <$pattern>
  @a=<c:/temp/*>; #it returns all file lists
  @a=glob("c:/temp/*); # same as above
  while ($filename=<c:/temp/*>) # return the next filename, the folder as well, in each iteration
  {
    print "one of the file name is $filename";
  }
 
   while ($filename=glob("c:/temp/*") # return the next filename, the folder as well, in each iteration
  {
    print "one of the file name is $filename";
  }
 
  #pls be notes although file blobbing and regular-expression matching function similarly
  #the meaning of the various special characters in quite different
  #the *,[] can be used in the pattern
 
 Directory Handlers
  opendir(DirectoryHandler,$pathname);
  readdir(DirectoryHandler); #in array context, it returns all fills , the folder as well, under the path. in scalar context, it returns the next file(folder) name under the path

  closedir(DirectoryHandler);

Monday, August 6, 2007

Format (Part 7)-- Perl Study Notes

Format (Part 7)-- Perl Study Notes

Format (Part 7)-- Perl Study Notes

 The steps to use format
 1. Define the format
 2. Loading up the data to be printed into the variable portions of the format.
 3. Invoking the format
 
 Define the format
  the syntax of the format definition
  format formathandler=   #format is the reserved word, it says it is a format definition. formathandler is the format name

  fieldline               #formatted pattern
  value_one,value_two,value_three  #the value can be scalar or expressions/functions which return the scalar variable.But pls note that if the fieldholder is type of "Filled Fields", value can just be scalar instead of expression or function.

  fieldline
  value_one,value_two,value_three
  ...        #you can add another fieldline
  ...        #you can add another value mapped above fieldline
  .          # indicate the format definition is done
 
 Example of the Format
  #the fixed text format example
  format FIXFORMAT=
  This is the string to be printed out
  .         

Wednesday, August 1, 2007

Function (Part 6)-- Perl Study Notes

Function (Part 6)-- Perl Study Notes

 Arguments
  @_ is a array of all arguments passed to the subroutines
  $_[0],$_[1],$_[2]is the first/second/third/... arguments passed to the subroutines
 
 Define local variable
  my ($localScalar); #define one local scalar variable localScalar
  my (@localArray);  #define one local array variable localArray
  my (%localHash); #define one local hash variable localHash
  my ($localScalar,@localArray,%localHash); #define 3 local variables,localScalar, localArray and localHash
  my ($localScalar,@localArray) = ("Scalar",qw(list1 list2 list3)); # define the local variable and initial the variable

 
  Notes, operator local can be used to define the local variable. But we should prefer to use my over local because it is faster and safe

  local $_; # can not write like my $_;
  local $1; # can write like my $1;
  local @ARGV; # can write like my @ARGV;
 
  Perl pragma
   use strict; # write this in the top of the code file can keep from using the variable without declaration
   The advantages of forcing variable declarations are as below
   1. Will run slightly faster.(variables created with my are accessed slightly faster than ordinary variables)
   2. Can keep from variables typing error

Tuesday, July 31, 2007

Control Structures (Part 3)-- Perl Study Notes

Control Structures (Part 3)-- Perl Study Notes

  Operator syntax
    if ($expression)
    {
    ....
    }
    elsif ($expression)
    {
    ...
    }
    else
    {
    ...
    }
   
    unless ($expression)
    {
    ...
    }
   
    while ($expression)
    {
    ...
    }
   
    until ($expression)
    {
    ...
    } 
   
    do
    {
    ...
    }  while ($expression)
   
    do
    {
    ...
    }  until ($expression)
   
    for($initial_exp1;$test_exp;$reinit_exp)
    {
    ...
    } 
   
    foreach $value (@list)
    {
    ...
    } # $value get each element in the @list
   
    foreach (@list)
    {
    ...
    } #$_ get each element in the @list
 
  How to populate true or false in Perl
    a. convert the expression to string
    b. if the string is empty or "0", it returns false else true
    "0" #false
    0 #false
    "00" #true
    undef #false
    1 #true
 
  last: to exit from the loop
  while (something) {
      something;
      something;
      something;
      if (somecondition) {
        somethingorother;
        somethingorother;
        last; # break out of the while loop
        }
      morethings;
      morethings;
  }
  # last comes here 
 
  next: to exit current loop and continue the next round loop
  while (something) {
      something;
      something;
      something;
      if (somecondition) {
        somethingorother;
        somethingorother;
        next; # break out of the while loop
        }
      morethings;
      morethings;
     # next comes here
  }
  
   redo: to jump to the beginning of the current block(without reevaluating the control expression)
   while (somecondition) {
      # redo comes here without evaluate the somecondition
      something;
      something;
      something;
      if (somecondition) {
        somethingorother;
        somethingorother;
        redo; # break out of the while loop
        }
      morethings;
      morethings;

   }   
   The follow is another loop structure without any while/for/foreach/until statement
   {
     startstuff;
     startstuff;
     startstuff;
     if (somecondition) {
     last;
     }
     laterstuff;
     laterstuff;
     laterstuff;
     redo;
    } # this block will be looped until somecondition is true
   
    Pls note that last/next/redo can not be used in the do{}while/until statement
   
    Expression Modifiers
    some_expression if control_expression
    this is equivalent to
    if(control_expression)
    {
    some_expression
    }
   
    exp2 unless exp1; # like : unless(exp1){exp2;}
    exp2 while exp1; #like: while(exp1){exp2;}
    exp2 until exp1; #like: until(exp1){exp2;}
   
    && and || Control Structures
    this && that; # equivalent to that if this
    this || that; # equivalent to that unless this

Regular Expression (Part 5)-- Perl Study Notes

Regular Expression (Part 5)-- Perl Study Notes

Single-Character Patterns
/a./; #. matches any characters except \n. /a./ matches any two-letter sequence that starts with a but except a\n
/a+/; #+ matches one or more of the immediately previous character, such as lookaab,aaabc but no lookup
/a*/; #* matches zero or more of the immediately previous character, such abs, asdic
/a?/; #? matches zero or one of the immediately previous character, such as abc,aabc
/[abcde]/; #match a string containing any one of the letters
/[^0-9]/; #match any single non-digit
/[^aeiouAEIOU]/; #match any single non-vowel
/[^/^]/; #match any character except an up-arrow
/[\da-fA-F]/; #match one hex digit
/\d/ # equivalent to /[0-9]/
/\D/ # equivalent to /[^0-9]/
/\w/ # equivalent to /[0-9a-zA-Z]/
/\W/ # equivalent to /[^0-9a-zA-Z]/
/\s/ #equivalent to /[\r\t\n\f]
/\S/ $equivalent to /[^\r\t\n\f]

Group Patterns
/x+box?/; # + means one or more of the immediately previous character and the ? means zero or one of the immediately previous character.

# the above pattern match the string "xbox","xxbo","xxbox"
/x{1,5}/; # match any string with one

Parentheses as memory
/fred(.)barney\1/; # \1 means the first parenthesized part of the regular expression.
# if matchs fredybarneyy but not fredybarneyx
/a(.)b(.)c\2d\1/; # matchs azbycydz but not abbccd
/a(.*)b\1c/; #match aFREDbFredC not axxbxxxc

Alternation Patterns
/songbule/; #matchs either song or blue

Anchoring Patterns
/fred\b/; # matches fred, but not frederick
/\bmo/; #matches moe but not emo
/\bFred\b/; #matchs Fred but not Frederick or alFred
/\b\+\b/; #matchs "x+y" but not "++" or " + "
/abc\bdef/; #never matchs
/\bFred\B/; #matchs "Frederick" but not "Fred Flintstone"
/^Fred/; #matchs Fredabc but not aFred
/Fred$/; #matchs abcFred but not Freda

Other operators
~/^he/; ~ to select a different target, for example
$a="hello world";
$a=~/^he/; #true, but $a still ="hello world"
$a=~/(.)\1/; #true, but $a still ="hello world"
if ($a=~/(.)\1/) #true
{
# put statement here
}

/abc/i; # i to ignore the case. it matches abs, Abs, ABC

/^\/usr\/etc/; # Using standard slash delimiter. It matches the string containing /urs/etc
m@^/usr/etc@; #using @ for a delimiter. It also matches the string /usr/etc
m#^/usr/etc#; #using # for a delimiter. It also matches the string /usr/etc
pls note that the delimiter must be any nonalphanumeric character

$what = "[box]"; #\Q will ignore any specify character in the regular expression
foreach (qw(in[box] out[box] white[sox])) {
if (/\Q$what\E/) {
print "$_ matched!\n";
}
}

Ready-Only Variable
# variable $1,$2,$3 and so on are set to the same values as \1,\2,\3, and so on
$_="this is a test";
if (/(\w+)\W+\(\w+)/)
{
print "$1\n"; # $1 = this
print "$2\n"; # $2 =is
}

#$& is the part of the string that matched the regular expression
#$` is the part of the string before the part that matched
#$' is the part of the string after the part that matched

Substitutions
the syntax of the substitutions is
s/old-regex/new-string/
If you want to the replacement to operate on all possible matches instead of just the first match, append a g to the substitution

$_="foot fool buffoon";
s/oo/bar/; # $_=fbart fool buffoon;
$_="foot fool buffoon";
s/oo/bar/g; # $_=fbart fbarl buffoon;
$_ = "this is a test";
s/(\w+)/<$1>/g; # $_ is now "<this> <is> <a> <test>"

$d{"abc"}=123;
$d{"def"}=456;
$d{"ghk"}=789;

foreach (keys %d)
{
print "$d{$_}\n";
$d{$_}=~s/^/x /; #prepend "x " to hash element
print "$d{$_}\n";
}
#we can see that the original string is changed after using regular expression substitutions.

#example for \G usage

$what = "[box]";

foreach (qw(in[box] out[box] white[sox]))

{ if (/\Q$what\E/) { # equivalent to match the regular expression of /\[box\]/

print "$_ matched!\n";

}

Monday, July 30, 2007

Basic I/O (Part 4)-- Perl Study Notes

Basic I/O (Part 4)-- Perl Study Notes

<STDIN>
while (defined($line = <STDIN>))
{
... # process $line here
}

Diamond Operator
a. The diamond operator gets its data form file or files specified on the command line that invoked the Perl program

for example, we have a pl file readfile.pl as below
#!/usr/bin/perl
while (<>)
{
print $_;
}
run the perl like this
readfile.pl file1 file2 file3
the diamond operator reads each line of file 1 and file2 and file3
b. In a scalar context, it returns a single line. In a list/array context, it returns all lines.
c. The daimond operator gets the files form the @ARGV. @ARGV is initiated by the parameters of the command line.The parameter can be assigned in the program itsefl. Here is the example,

#!/usr/bin/perl
@ARGV=qw(file1,file2,file3)
while (<>)
{
print $_;
}

<STDOUT>
print (2+3),"hello"; # wrong! prints 5, ignores "hello"
print ((2+3),"hello"); # right, prints 5hello
print 2+3,"hello"; # also right, prints 5hello


Filehanlers
open (FILEHANDLE,$filewanttoopen); #open external file or device $filewanttoopen, return true if success and false if fail
open FILEHANDLE, ">$filewanttowrite); # open the file $filewanttowrite to write, return true if success and false if fail
open FILEHANDLE, ">>$filewanttoappend); # open the file $filewanttoappend for appending, return true if success and false if fail
close(FILEHANDLE); #close the FILEHANDLER

Pls note reopen the FILEHANDLE can close it automatically.


die and warn
die("This is the error message!!!"); # print out "This is the error message!!!" followed the program name and line number and exit the perl.
die("This is the error message!!!\n"); # just print out "This is the error message!!!" followed the program name and line number and exit the perl.
warn("This is the error message!!!"); # just print out the string "This is the error message!!!" without terminate the perl

#!c:\perl\bin\perl.exe
# here is the example to copy file $a to $b
open(IN,$a) die "cannot open $a for reading: $!";
open(OUT,">$b") die "cannot create $b: $!";
while () { # read a line from file $a into $_
print OUT $_; # print that line to file $b
}
close(IN) die "can't close $a: $!";
close(OUT) die "can't close $b: $!";


File tests operator (Most used)
-e $filename; return true if $filename is existing while false if not.
-r $filename; return true if $filename is readable while false if not.
-w $filename; return true if $filename is writable while false if not.
-x $filename; return true if $filename is executable while false if not.
-s $filename; return size of the $filename if $filename is existing.
-M $filename; return days since the $filename is last modified.
-A $filename; return days since the $filename is last accessed.
-C $filename; return days since the inode of the $filename changes.

Thursday, July 26, 2007

Data Type (Part 2 - Array/Hash Variable)-- Perl Study Notes


Data Type (Part 2 - Array/Hash Variable)-- Perl Study Notes 

Array Variable
 Array operator: ..
    (1 .. 5) # same as (1,2,3,4,5)
    (1.1 ..5.1) #same as (1.1,2.1,3.1,4.1,5.1)
    (3.2 .. 5.1) #same as (3.2,4.2)
    Notes: .. operator create a list of values starting at the left scalar value up through the right scalar value incrementing by one each time

           Having the right scalar less than the left scalar results in an empty list
           If the final value is not a whole number of steps above the initial value, the list stops just before the next value would have been outside the range,just as the above sample

           Only effective to the number lists
 
 Array example,
  @fred=qw(4 5 6);
  @fred=(4,5,6);
  $a=@fred; # $a=3, If one array is assigned to a scalar variable, the number assigned is the length of the array.
  ($a)=@fred; $a=4, only assign the first value to the $a.
  @fred=("fred", "wilma", "pebbles", "dino");
  $fred[-1]; # return "dino"
  $#fred;  #return 3. $#array_name returns the last index of the array
 
Hash Variable
 Hash example,
  $fred{"aaa"} = "bbb"; # creates key "aaa", value "bbb"
  $fred{234.5} = 456.7; # creates key "234.5", value 456.7
  if %hash {...} # in the scalar context, merly using %hash will reveal whether the hash is empty or not

 Hash Slices
  @score{"fred","barney","dino"} = (205,195,30);
  @players = qw(fred barney dino);
   print "scores are: @score{@players}\n"; # scores are: 205 195 30

Wednesday, July 25, 2007

Data Type (Part 1 - Scalar Variable) -- Perl Study Notes

Data Type (Part 1- Scalar Variable)

Scalar Variable

number: including the integer and float number. all number will be converted into double in internal perl
1000
10.24
1.25e45
012 #Octal number
0x12 #Hex number

number operator: +-*/%

number logical comparion: > < == >= <= !=

string: single-quoted strings
'hello' #hello
'don\'t' #don't
'silly\\me' #silly\me
'hello\n' #hello\n
'hello $name' # hello $name
double-quoted strings
"hello world\n" # hello world and new line
"coke\tsprite" #coke+a tab+sprite
"my name is $name" #my name is zhengol, if $name="zhengol"

string operator:. x
"abc"."def" #abcdef
"abc"x4 #abcabcabc
(3+2)x5 #55555

string logical comparaion: eq lt gt ne le ge

Notes: the numeric and string comparions are roughly oppposite of what they are for the Unix which uses -eq for string comparison and == for numeric comparison

(To be continued)