Thursday, January 16, 2014

tool #2 : perl

$perl -v
#!/usr/bin/perl
Perl is a case sensitive programming language. 

#######################################
1. Comment 
#######################################
=blah...
blah...
=cut
 
OR 
 
# blah...

#######################################
2. Data Types
#######################################
S.N. Types and Description
a) Scalar:
   Scalars are simple variables. preceded by a dollar sign ($). 
   A scalar is either a number, a string, or a reference. 
   A reference is actually an address of a variable which we will see in upcoming chapters.
b) Arrays:
   Arrays are ordered lists of scalars. preceded by an "at" sign (@).
c) Hashes:
   Hashes are unordered sets of key/value pairs. preceded by a percent sign (%).

d) Numeric Literals
   numbers: signed integers or 
     double-precision floating-point values. 

   Type                Value
   Integer             1234
   Negative integer    -100
   Floating point      2000
   Scientific notation 16.12E14
   Hexadecimal         0xffff
   Octal               0577

e) String Literals
   either single (') or double (") quotes. 

   $age = 25;                      # An integer assignment
   $name = "John Paul";            # A string 
   $str = "hello" . "world";       # Concatenates 
   $salary = 1445.50;              # A floating point
   @ages = (25, 30, 40);    
   %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
   $ages[0]
   $data{'John Paul'}

f) Special Literals
   print "File name ". __FILE__ . "\n";
   print "Line Number " . __LINE__ ."\n";
   print "Package " . __PACKAGE__ ."\n";

##############################
3. Array 
##############################
a) Array Creation
   @array = (1, 2, 'Hello');
   @array = qw/This is an array/;
   @var_10 = (1..10);
   @var_abc = (a..z);

   @array = (1,2,3);
   $size = @array;
   $max_index = $#array;

b) Array : add + remove
   @coins = ("Quarter","Dime","Nickel");   # create a simple array
   push(@coins, "Penny");                  # add element: [....] elem
   unshift(@coins, "Dollar");              # add element : elem [...]
   pop(@coins);                            # remove element : [... elem]
   shift(@coins);                          # remove element : [elem ...]

c) Array slice
   @weekdays = @days[3,4,5];
   @weekdays = @days[3..5];

##############################
4. Hash
##############################
a) hash creation ( map:   key=>value OR key, value )
   %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar', 40, 'Young', 33);
   %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar', 40, 'Young');     # 'Young' missing value
   %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40, 'Young');        
   @keys = keys %data;    # get key values
   @ages = values %data;  # get all values 

b) hash : add + delete 
   $data{'Ali'} = 55;      # add 
   delete $data{'Ali'};    # delete

c) check hash existence
   if( exists($data{'Lisa'} ) ){  
     print "Lisa is $data{'Lisa'} years old\n"; 
   } else { 
     print "I don't know age of Lisa\n"; }

#############################
The ? : Operator
#############################
   Exp1 ? Exp2 : Exp3;

########################################
5. Loop : next, last, continue & goto
########################################
   while($a < 10){
      if( $a == 5 ){
        $a = $a + 1;
        next;     # do execute continue-statement, it's similar to "continue in java"
      }
      print "Value of a = $a\n";
   }continue{     # it's similar to "finally in java"
      $a = $a + 1;
   }

   while( $a < 20 ){
      if( $a == 15) {
        $a = $a + 1;
        last;     # it's similar to "break in java"
      }
      print "value of a: $a\n";
      $a = $a + 1;
   }

   LOOP:do {
     if( $a == 15){
       $a = $a + 1;
       goto LOOP;    # it's similar to "goto in Fortran"
     }
     print "Value of a = $a\n";
     $a = $a + 1;
   }while( $a < 20 );

#################################
6. Perl operations
#################################
a) Perl Arithmetic Operators:
   + - * / % **(exponent) 
b) Perl Equality Operators:
   == != <=>  > < >= <=
c) Perl String comparison: 
   lt gt le ge eq ne cmp ( similar to <=> ) 
d) Perl Assignment: 
   = += -= *= /= 5= **=  
e) Perl Bitwise operations: 
   & | ^ ~ << >> 
f) Perl logical operations: 
   and && or || not 
g) Quote-like Operators:
   q{ }  Encloses a string with single quotes q{abcd} gives 'abcd'
   qq{ } Encloses a string with double quotes qq{abcd} gives "abcd"
   qx{ } Encloses a string with invert quotes qx{abcd} gives `abcd`
h) Miscellaneous Operators:
   ( .  ) concatenates two strings
   ( x  ) repeated. ('-' x 3) will give '---'.
   ( .. ) range from left value to right value, (2..5) will give (2, 3, 4, 5)
   ( ++ ) increases integer value by one, $a++ will give 11
   ( -- ) decreases integer value by one, $a-- will give 9
   ( -> ) dereferencing a method or variable from an object or a class name

######################################
7. Function
######################################
a) definition 
   sub function1 {       # Note: no () after function name
      blah......         # no return-statement 
   }

   sub Average{
      blah...
      return $result;    # return-statement
   }

b) call function
   &function1();
   $num = &Average(10, 20, 30);

c) parameters passed to function as array @_
   sub Average{
      $n = scalar(@_);     # number of params
      my (@list) = @_;     # save array as array
      foreach $item (@list){
        print $item;
      }
      my (%hash) = @_;     # save array as hash 
      foreach $item (%hash){
        print "Item : $item\n";
      }
   }

$num = &Average(10, 20, 30);

d) private variable in subrouine
sub somefunc {
   my $variable; # invisible outside somefunc()
   my ($another, @an_array, %a_hash); # declaring many variables at once
}

e) temporary values via local()
   sub PrintHello{
      local $string;    # global variable to nested functions. 
      PrintMe();
   }
   sub PrintMe{
      print "Inside the function PrintMe $string\n";
   }


####################################
8. Reference type 
####################################
a) Create References:

   This is simple to create a reference for any variable, subroutine or value 
   by prefixing it with a backslash as follows:

   $scalarref = \$foo;
   $arrayref  = \@ARGV;
   $hashref   = \%ENV;
   $funcref   = \&handler;  # ref to function 
   $globref   = \*foo;      # ref 

   $arrayref = [1, 2, ['a', 'b', 'c']];
   $hashref = { 'Adam'  => 'Eve', 'Clyde' => 'Bonnie', };

b) dereference
   To dereference a reference simply use $, @ or % as prefix of the reference variable 
   depending on whether reference is pointing to a scalar, array, or hash.
   print $$scalarref;
   print @$arrayref;
   print %$hashref;
   print &$funcref;
   print *$globref;


# Function call using reference.
  &$cref(%hash);

#################################
9. file operations
#################################
a) open file mode
   open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";
       <   or r  Read Only Access
       >   or w  Creates, Writes, and Truncates
       >>  or a  Writes, Appends, and Creates
       +<  or r+ Reads and Writes
       +>  or w+ Reads, Writes, Creates, and Truncates
       +>> or a+ Reads, Writes, Appends, and Creates

   close(DATA) || die "Couldn't close file properly";

   while(<DATA>){
     print "$_ ";     # each line is saved into $_
   }

b) read file operations
   getc FILEHANDLE
   getc
   read FILEHANDLE, SCALAR, LENGTH, OFFSET
   read FILEHANDLE, SCALAR, LENGTH
   print FILEHANDLE LIST
   print LIST
   tell FILEHANDLE
   tell
   seek FILEHANDLE, POSITION, WHENCE
   rename ("/usr/test/file1.txt", "/usr/test/file2.txt" );  # rename file
   unlink ("/usr/test/file1.txt");                          # delete file

   eg:  read DATA, $a, 100   # read first 100 chars and saved into $a

   my $file = "/usr/test/file1.txt";
   my (@description, $size);
   if (-e $file) {
      push @description, 'binary' if (-B _);
      push @description, 'a socket' if (-S _);
      push @description, 'a text file' if (-T _);
      push @description, 'a block special file' if (-b _);
      push @description, 'a character special file' if (-c _);
      push @description, 'a directory' if (-d _);
      push @description, 'executable' if (-x _);
      push @description, (($size = -s _)) ? "$size bytes" : 'empty';
      print "$file is ", join(', ',@description),"\n";
   }

c) file manipulation operations
   # Display all the C source files in /tmp directory.
   $dir = "/tmp/*.c";   @files = glob( $dir );
   foreach (@files ){ print $_ . "\n"; }

########################################
10. Error Handling
########################################
Errors within modules : similar to java stacktrace report
   die : exit
   warn, carp, cluck, croak & confess : exception throw

a) two simplifications 
   if(open(DATA, $file)){ 
      ...
   }else{
      die "Error: Couldn't open the file - $!";
   }
      || 
      ||  simplified to 
      \/
   open(DATA, $file) || die "Error: Couldn't open the file $!";

   unless(chdir("/etc")){
      die "Error: Can't change directory - $!";
   }
      || 
      ||  simplified to 
      \/
   die "Error: Can't change directory!: $!" unless(chdir("/etc"));


#####################################
11. Miscellaneous stuff
#####################################
a) Global Scalar Special Variables
   $_  The default input and pattern-searching space.
   $ARG
   $.  The current input line number of the last filehandle that was read.

b) regular expression
   The basic method for applying a regular expression is to use 
   the pattern binding operators =~ and !~. 
   The first operator is a test and assignment operator. 
   There are three regular expression operators within Perl

    - Match Regular Expression - m//
    - Substitute Regular Expression - s///
    - Transliterate Regular Expression - tr///

c) The Match Operator
   The match operator, m//, is used to match a string or statement to a regular expression. 
   For example, to match the character sequence "foo" against the scalar $bar, you might use 
   a statement like this:

d) Match Operator Modifiers
   Modifier Description
   i Makes the match case insensitive
   m Specifies that if the string has newline or carriage return characters, 
        the ^ and $ operators will now match against a newline boundary, 
        instead of a string boundary
   o Evaluates the expression only once
   s Allows use of . to match a newline character
   x Allows you to use white space in the expression for clarity
   g Globally finds all matches
   cg Allows the search to continue even after a global match fails

c) The Substitution Operator
   The substitution operator, s///, is really just an extension of the match operator 
   that allows you to replace the text matched with some new text. The basic form of the 
   operator is:

   s/PATTERN/REPLACEMENT/;

d) The Translation Operator
   Translation is similar, but not identical, to the principles of substitution, 
   but unlike substitution, translation (or transliteration) does not use regular 
   expressions for its search on replacement values. The translation operators are:

No comments:

Post a Comment