Search This Blog

Wednesday, 26 June 2013

Perl scripting

PERL (Practical Extraction Report language)

  • Perl is developed by "Larry Wall" in 1986.

  • The home of the Perl is Unix

  • Perl is written in "C" language.

  • Perl is interpreter based language.

  • Perl is a case sensitive scripting language.
Differences between Scripting Language and Programming Language
Scripting Language
  1. It is an Interpreter based language.

  2. Interpreter converts high level instructions into machine language line by line.

  3. It doesn’t create .exe file.

  4. No need to compile the source code.

  5. It takes less lines of code.

  6. It reduces cost of maintenance

  7. Basically this executes at server side.
  8. Programming Language
    1. It is a compiler based language.

    2. Compiler converts whole program in single shot into machine language.

    3. It creates .exe file.

    4. Needs to compile the program.

    5. It takes numerous lines of code.

    6. It increases cost of maintenance.

    7. These are used for client based applications.
    8. The perl borrowed many features from Unix utilities (like awk, sed, grep, tr ) and added "C" language functionality.
      The features of Perl
      1. Free software.

      2. Open source code.

      3. It is simple and easy to learn.

      4. It is rich in procedural and object oriented.

      5. It is highly portable language i.e The Perl programs are written in one platform allows to run in another platform with or without modifications.

      6. Perl supports DB Connectivity.

      7. Perl supports CPAN (Comprehensive Perl Archive Network) modules. You can refer the following website for CPAN modules ;
      8. www.cpan.org
      9. The Perl initially designed for to do manipulations in text files, later it is used in wide range of the following areas

        • System Administration

        • Database Administration

        • Web Development (CGI)

        • Networking (Net)

        • Bioinformatics (Bio)

        • Testing (Test)

        • VLSI

        • Telecom

        • GUI development
      10. The extension of the Perl program is ".pl".

      11. The name of the Perl interpreter is "perl"

      12. The motto of the Perl is more than one way to do it.

      13. Perl supports 2 types of comments.

        • Single line comment (#)

        • Multi line comment
          =pod (plan old documentation)
          ------------------
          ------------------
          ------------------
          =cut
          How to run Perl programs on windows platform
          1. Open text editor (notepad)

          2. Write Perl program

          3. Save program with .pl extension

          4. Run program at command prompt C:\>perl program.pl
          5. How to run Perl programs on Linux platform
            1. Open text editor (vi)

            2. Write Perl program

            3. Save and quit from the vi editor

            4. Run the program at $ prompt ;
            5. $perl program.pl
              $chmod a+x program.pl
              $./program.pl
              How to see location of the Perl?
              $which perl ß
              /usr/bin/perl
              How to see the help in Linux?
              $man perl
              How to see the version of the perl?
              $perl –v
              Write a program to print welcome message?
              #!/usr/bin/perl -w
              #Author: Pavankumar
              # -w displays warnings
              print "welcome to SEI \n";
              print "This is my first perl program \n";



              Variable
              1. It is a data name or memory location

              2. It is a temporary storage location

              3. It value can change during the execution of the program

              4. Perl allows implicit variable declaration i.e. No need to declare the variables explicitly by programmer

              5. Every variable occupies memory during execution time

              6. Variables are classified into 3 types

                • Scalar variables

                • Array variables or Indexed array variables

                • Hash array variables or Associated array variables
                  Scalar variables
                  • It holds only one value

                  • The value may be integer/float/string

                  • It should begin with "$" symbol
                  • Array variables
                    • It is a group of scalar variables

                    • It should begin with "@" symbol
                    • Hash array variables
                      • It is a group of key pair values

                      • It should begin with "%" symbol
                      • Print:
                        "print" is a predefined function and it is used for to write data to the output screen.
                        Ex: print ("Hello");
                        print "Hello";
                        print STDOUT "Hello";
                        #hello.pl
                        #!/usr/bin/perl -w
                        print ("hello, perl\n");
                        print "hello, perl\n";
                        print STDOUT "hello, perl\n";
                        The standard input/output/error buffers are
                        • STDIN

                        • STDOUT

                        • STDERR
                        <STDIN> is the standard input handler used to take input from user.
                        <STDOUT> is the standard output handler used to write data to the screen.
                        <STDERROR> is the standard error handler used to write errors.





                        #Write a program to accept the name and display
                        #prg2-chomp.pl
                        #!/usr/bin/perl -w
                        print "Enter a name:";
                        $name=<STDIN>; #<> -- Diamond operator
                        chomp($name);
                        print "Hello, $name, How are you?\n";
                        print "Enter a name:";
                        chomp($name=<STDIN>);
                        print "Hello $name, How are you?\n";
                        print "Enter a name:";
                        chomp($name=<>); # By default it reads input from the keyboard
                        print "Hello $name, How are you?\n";
                        Note:
                        "chomp" is a predefined function, it deletes the given string last character, if it is new line character
                        Scalar variable Examples
                        $a=100; # integer
                        $b=10.5; # float
                        $course="perl"; # String
                        $name=’Tecno soft’; #String
                        $k="100"; # String
                        $m="25.67"; #String
                        #prg-scalar.pl
                        #!/usr/bin/perl -w
                        $a=100; # integer
                        $b=10.5; # float
                        $course="perl"; # String
                        $name='Tecno soft'; #String
                        $k="100"; # String
                        $m="25.67"; #String
                        print "a=$a, b=$b, course=$course, name=$name, k=$k, m=$m\n";
                        Strings are classified into 3 types
                        Double quoted strings (" ") qq// or qq{} or qq() or qq<> or qq[]
                        Single quoted string (‘ ‘) q// or q{} or q() or q<> or q[]
                        Back quoted strings or Back tick strings (` `) qx// or qx{} or qx() or qx<> or qx[]
                        Ex1:
                        $str="perl";
                        $x="I like $str";
                        print $x;
                        Ex2:
                        $str="perl";
                        $x=’I like $str’;
                        print $x;
                        Ex3:
                        $str="perl";
                        $x="I like \n $str";
                        print $x;
                        Ex4:
                        $str="perl";
                        $x=’I like \n $str";
                        print $x;
                        Note:
                        In double quoted strings, variable substitution takes place but in single quoted strings, every thing it treats as normal text.
                        $str = "I said, "Don’t write to dist""; -- Incorrect
                        $str = "I said, \"Don’t write to disk\"’; -- Correct
                        $str = ‘I said, "Don\’t write to disk"’; -- Correct
                        #!/usr/bin/perl -w
                        $x = "disk";
                        $str = qq/I said, "Don’t write to $x"\n/;
                        print $str;
                        Output:
                        I said, "Don’t write to disk
                        #!/usr/bin/perl -w
                        $x = "disk";
                        $str = "q/I said, "Don’t write to $x"\n/;
                        print $str;
                        Output:
                        I said, "Don’t write to $x\n"
                        Back quote (``): It is used to execute operating system commands.
                        #!/usr/bin/perl -w
                        $x=`ls -lrt`;
                        print $x;
                        #!/usr/bin/perl -w
                        $x=qx/who/;
                        print $x;



                        Operators:
                        Arithmetic operators
                        : + - * / % **
                        Ex1:
                        $a=10;
                        $b=4;
                        print $a+$b; #14
                        Ex2:
                        $a=10;
                        $b="25abc";
                        print $a+$b; #35
                        Ex3:
                        $a=10;
                        $b="abc25";
                        print $a+$b; #10
                        Ex4:
                        $a="Hello";
                        $b="Pavan";
                        print $a+$b; #0
                        Ex5:
                        $a=10;
                        $b="456abc";
                        print $a+$b; #466
                        Ex6:
                        $a=10;
                        $b="25abc";
                        print $a+$b; #35
                        print $a.$b; #1025abc
                        Ex7:
                        $a=2
                        $b=4
                        print $a**$b; #2**4=16
                        Relation operators:
                        a) Numeric comparison operators
                        : <, >, <=, >=, = =, ! =, <=> (Three way comparison operator)
                        b) String comparison operators:
                        lt, gt, le, ge, eq, ne, cmp (Three way comparison operator)
                        Ex1:
                        $a=100;
                        $b=20;
                        $a>$b ---- True
                        $a gt $b ---- False
                        Ex2:
                        $x ="hello";
                        $y ="pavan";
                        $x gt $y --- True
                        $x > $y --- False
                        Ex3:
                        $c = $a <=> $b;
                        If a>b à 1
                        a<b à -1
                        a= =b à 0
                        Ex4:
                        $k = $x cmp $y
                        If x>y à 1
                        x<y à -1
                        x= =y à 0
                        Logical operators:
                        &&, ||, ! or and, or, not
                        Sting multiplication operator:
                        x
                        $str = "perl";
                        $k = $str x 5; # It multiplies str by 5 times
                        print $k; # perlperlperlperlperl
                        String concatenation operator:
                        $str1 = "SEI";
                        $str2 = "Investments";
                        a) $k = $str1.$str2;
                        print $k; #SEIInvestments
                        b) $k = $str1." ".$str2;
                        print $k; #SEI Investments
                        Range operator:
                        1..10 ----- Correct
                        a..z ------ Correct
                        -10..-1 ---- Correct
                        10..1 ---- Incorrect
                        z..a ----- Incorrect
                        -1..-10 ---- Incorrect
                        print 1..10 # It prints no’s 1 to 10
                        Assignment operators:
                        $a = 10;
                        $b = 20;
                        $c = 30;
                        Or ($a,$b,$c)=(10,20,30)
                        Short hand assignment operator:
                        +=, -=, *=, !=, %=, .=, x=
                        Ex:
                        1. $a=10;

                        2. $a=$a+5; (or) $a+=5;
                        3. $str="load";
                        $str=$str."ing"; (or) $str.="ing";
                        Increment operator: ++
                        $a = 10;
                        $a = $a+1; (or) $a+=1; (or) $a++;
                        Decrement operator: --
                        $a = 10;
                        $a = $a-1; (or) $a-=1; (or) $a--;
                        IF Statements:
                        1. Simple if
                        2. if(condition)
                          {
                          ------------
                          ------------
                          }
                          -------------
                          -------------
                        3. simple unless
                        4. unless(condition)
                          {
                          -------------
                          -------------
                          }
                          -------------
                          -------------
                        5. if….else
                        6. if(condition)
                          {
                          ------------
                          ------------
                          }
                          else
                          {
                          -----------
                          -----------
                          }
                          -----------
                          -----------
                        7. unless…else
                        8. unless(condition)
                          {
                          ------------
                          ------------
                          }
                          else
                          {
                          ------------
                          ------------
                          }
                          --------------
                          --------------
                        9. if…elseif…
                        10. if(condition)
                          {
                          ------------
                          ------------
                          }
                          elsif(condition)
                          {
                          -------------
                          -------------
                          }
                          else
                          {
                          ------------
                          ------------
                          }
                        11. single line if statement
                        12. statement1 if(condition);
                          ---------------
                          ---------------
                        13. Single line unless statement
                        Statement1 unless(condition);
                        ------------------
                        ------------------
                        Looping statements:
                        1. while loop
                        while(condition)
                        {
                        -----------
                        -----------
                        }
                        ---------
                        ---------
                      • until loop
                      • until(condition)
                        {
                        -----------
                        -----------
                        }
                        -----------
                        -----------
                      • do…while loop
                      • do
                        {
                        -----------
                        -----------
                        }
                        while(condition);
                      • do…until loop

                      • do
                        {
                        -----------
                        -----------
                        }
                        while(condition);
                        ------------
                        ------------
                      • for loop
                      • for(initialization;condition;incr/decr)
                        {
                        ---------------
                        ---------------
                        }
                        --------------
                        --------------
                      • foreach loop
                      • foreach variable(list of values)
                        {
                        --------------
                        --------------
                        }
                        ------------
                        ------------
                        last :
                        It is used for to terminate the loop.
                        next:
                        It is used for to start the loop again.
                        while(condition)
                        {
                        ------------
                        ------------
                        last;
                        ------------
                        ------------
                        }
                        -----------
                        -----------
                        while(condition)
                        {
                        -------------
                        -------------
                        next;
                        -------------
                        -------------
                        }
                        -------------
                        -------------
                        Programs on if statements:
                        #write a program to accept a number and check the no is an even or odd?
                        #!/usr/bin/perl -w
                        print "\nEnter number:";
                        chomp($n=<STDIN>);
                        if($n%2==0)
                        {
                        print "\n$n is an Even no\n";
                        }
                        else
                        {
                        print "\n$n is an Odd no\n";
                        }
                        #WAP Accept a number and check the no is 3 digit no or not?
                        #!/usr/bin/perl -w
                        print "\nEnter a number:";
                        chomp($n=<STDIN>);
                        if($n>=100&&$n<=999)
                        {
                        print "\n$n is a 3 digit number\n";
                        }
                        else
                        {
                        print "\n$n is not a 3 digit number\n";
                        }
                        #WAP to accept username and password and check the user is valid or not?
                        #!/usr/bin/perl -w
                        print "\nEnter Username:";
                        chomp($username=<STDIN>);
                        print "\nEnter Password:";
                        chomp($password=<STDIN>);
                        if($username eq "pbandaru" && $password eq "pbandaru")
                        {
                        print "\nWelcome to SEI\n";
                        }
                        else
                        {
                        print "\nInvalid username or password\n";
                        }
                        #WAP to accept 2 strings and check string1 >string2 or string1<string2 or both strings are equal?
                        #!/usr/bin/perl -w
                        print "\nEnter a string1:";
                        chomp($str1=<STDIN>);
                        print "\nEnter a string2:";
                        chomp($str2=<STDIN>);
                        $x=($str1 cmp $str2);
                        if($x = =1)
                        {
                        print "\n$str1 is greater than $str2\n";
                        }
                        elsif($x = =-1)
                        {
                        print "\n$str1 is less than $str2\n";
                        }
                        elsif($x = =0)
                        {
                        print "\nboth are equal\n";
                        }

                        #WAP to check whether variable exist or not?
                        #!/usr/bin/perl -w
                        $a=10;
                        undef($a); #undef function is used for to delete a variable
                        if(defined($a)) #defined function returns true, if the variable defined otherwise false
                        {
                        print "variable exist\n";
                        }
                        else
                        {
                        print "No such variable\n";
                        }
                        Looping Statements:
                        #WAP to print numbers from 1 to 10
                        #!/usr/bin/perl -w
                        $i=1;
                        while($i<=10)
                        {
                        print "$i\t";
                        $i++;
                        }
                        print "\n\n\n";
                        for($i=1;$i<=10;$i++)
                        {
                        print "$i\t";
                        }
                        print "\n\n\n";
                        foreach $i (1..10)
                        {
                        print "$i\t"
                        }
                        print "\n\n\n";
                        foreach (1..10)
                        {
                        print "$_\t"; #$_ is a special variable which stores the default values
                        }
                        print "\n";
                        Arrays:
                        1. It is a collection of scalar variables. i.e collection of dissimilar type of values

                        2. It should begin with @ symbol

                        3. It has an infinite length

                        4. The array index starts with ‘0’
                        5. Syntax: @array_variable=(list of scalars);
                          Ex: @num=(10,20,30,40,50,60);
                          @x=(10,’perl’,4.5,60,"unix");
                          @days=("sun","mon","tue","wed",’thu","fri","sat");
                          @days=qw(sun mon tue wed thu fri sat);
                          Accessing array elements
                          print "@num"; #10 20 30 40 50 60 à With space
                          print @num; #102030405060 à Without space
                          print $num[2]; #30 à Prints third element
                          print "@num[1..4]";#20 30 40 50 à Prints elements 1 to 4
                          print "$num[-1]"; #60 à It prints the last element
                          print "@num[0,1,-1,-2]";10 20 60 50 à More than one element array representation
                          EX:
                          #!/usr/bin/perl -w
                          @num=(10,20,30,40,50,60);
                          print "@num"; #10 20 30 40 50 60 With space
                          print "\n";
                          print @num; #102030405060 Without space
                          print "\n";
                          print $num[2]; #30 Prints third element
                          print "\n";
                          print "@num[1..4]"; #20 30 40 50 Prints elements 1 to 4
                          print "\n";
                          print "$num[-1]"; #60 It prints the last element
                          print "\n";
                          print "@num[0,1,-1,-2]"; #10 20 60 50 More than one element array representation
                          print "\n";
                          Writing elements to array
                          $num[6]=70;
                          $num[3]=100;
                          @num[7..10]=(100,200,300,400); # It overwrites if it exists, if not creates.
                          $num[100]="abc"; # If the last index is 50 then it creates remaining indexes before 100.
                          EX:
                          #!/usr/bin/perl
                          @num=(10,20,30,40,50,60);
                          $num[6]=70; # It will create a new index and add an element
                          print $num[6];
                          print "\n";
                          $num[3]=100; # It will overwrite the existing element
                          print $num[3];
                          print "\n";
                          @num[7..10]=(100,200,300,400);
                          print "@num";
                          print "\n";
                          $num[100]="abc";
                          print "$num[100]";
                          print "\n";
                          $#array:
                          It returns the last index of the array.
                          EX:
                          #!/usr/bin/perl -w
                          @num=(10,20,30,40,50,60);
                          print "\nnum array last index is: $#num"; #5
                          print "\nTotal elements in num array is:",$#num+1; #6
                          print "\n";
                          $num[$#num+1]="hello";
                          @k=@num; #copying array
                          print "Copied array elements are:@k";
                          print "\n";
                          $n=@num; #Assigining lenth of the array
                          print "Length of the array is:$n"; #7
                          print "\n\n";
                          EX:
                          #!/usr/bin/perl -w
                          @x=(10,20,30,40,50,60);
                          $i=0;
                          while($i<=$#x)
                          {
                          print "$x[$i]\n";
                          $i++;
                          }
                          print "\n";
                          @y=(10,20,30,40,50,60);
                          for($i=0;$i<=$#y;$i++)
                          {
                          print "$y[$i]\n";
                          }
                          print "\n";
                          @z=(10,20,30,40,50,60);
                          foreach (@z)
                          {
                          print "$_\n";
                          }
                          print "\n";
                          EX:
                          #!/usr/bin/perl -w
                          print "Enter elements to store into array at end press ctl+d:";
                          chomp(@a=<STDIN>);
                          print "Entered elements are\n";
                          foreach $x (@a)
                          {
                          print "$x \n";
                          }
                          print "\n Total no of elements:",$#a+1;
                          print "\n";

                          EX:
                          #!/usr/bin/perl -w
                          #Accept n integer elements and store into array and find sum and display
                          print "Enter no of elements:";
                          chomp($n=<STDIN>);
                          $i=0;
                          $total=0;
                          while($i<$n)
                          {
                          print "\n Enter number:",$i+1,":";
                          chomp($a[$i]=<STDIN>);
                          $total=$total+$a[$i];
                          $i++;
                          }
                          print "\n given elements are:\n";
                          print "@a\n";
                          print "\nSum of above elements:$total";
                          print "\n"
                          Hash Array Variable:
                          It is a group of key pair values
                          It should begin with % symbol
                          %variable = (list of key pairs)
                          Examples
                          %names=("hari",10000,"venkat",9500,"neeraja",8000,"sai",9800);
                          %name=("hari"=>10000,"venkat"=>9500,"neeraja"=>8000,"sai"=>9800);
                          %cities=("ap"=>"hyd","tn",=>"chennai","kn"=>"bangalore");
                          Hash Array Functions:
                          Keys:
                          It returns the given hash array keys
                          keys%hasharrayname;
                          eg: keys%cities
                          output: ap tn kn
                          Values:
                          It returns the given hash array values
                          values%hasharrayname;
                          eg: values%cities
                          output: hyd chennai bangalore
                          each:
                          It returns the given hash array one key pair value
                          each%hasharrayname
                          eg: each%cities
                          output: tn chennai
                          exists:
                          It returns true if the given key exist in the given array
                          exists%hasharrayname
                          delete:
                          It deletes the given key pair from the given hash array
                          delete $hasharrayname{key};
                          eg: delete $cities{m};
                          Ex: print-hash-array-element.pl
                          #!/usr/bin/perl -w
                          %names=("anu"=>4000,"madhu"=>8000,"latha"=>3000,"hari"=>9000,"babu"=>5000,"balu"=>4000,"anu"=>2000);
                          foreach $x (keys%names)
                          {
                          print "\n$x salary is: $names{$x}\n";
                          }
                          print "\n";
                          EX: print-hash-array-element1.pl
                          #!/usr/bin/perl -w
                          %names=("anu"=>4000,"madhu"=>8000,"latha"=>3000,"hari"=>9000,"babu"=>5000,"balu"=>4000,"anu"=>2000);
                          while(($x,$y)=(each%names))
                          {
                          print "\n$x salary is: $y\n";
                          }
                          $x=keys%names;
                          print "\n";
                          print "total no of variables:$x";
                          print "\n";
                          File Handling:
                          File:
                          It is collection of data or group of records
                          The following are functions to handle files
                          open():
                          It is used for to create a new file or to open an existing file or to append data to the existing files.
                          open(FILEHANDLE,"mode Filename");
                          FILEHANDLE is a user defined name
                          Modes are classified into 3 types
                          1. read mode (<) – Default mode

                          2. write mode (>)

                          3. append mode (>>)
                          How to open a file
                          Syn: open(FILEHANDLE,"<filename");
                          Ex: open(FH,"<sample.txt");
                          Note: In read mode if the given file exists, it opens a file and places a file pointer at the beginning of the file and returns true. If the file doesn’t exist, it fails to open file and returns false.
                          How to create a file
                          Syn:open(FILEHANDLE,">filename");
                          Ex: open(FH,">sample.txt");
                          Note: In write mode if the given file exists, it opens a file and deletes all file contents and places a file pointer at the beginning of the file. If the file doesn’t exist, it creates a new file and places file pointer at the beginning of the file.
                          How to append data to the file
                          Syn: open(FILEHANDLE,">>filename");
                          Ex: open(FH,">>sample.txt");
                          Note: In append mode if the given file exists, it opens a file and places a file pointer at the end of the file. If the file doesn’t exist, it creates a new file and places file pointer at beginning of the file.
                          close():
                          It is used for to close file, which is already opened
                          Syn: close(FILEHANDLE);
                          File Test commands:
                          -f:
                          It returns true if the given file is a regular file
                          -d:
                          It returns true if the given file is a directory file
                          -l:
                          It returns true if the given file is a link file
                          -e:
                          It returns true if the given file is exist
                          -z:
                          It returns true if the given file is empty
                          -r:
                          It returns true if the given file has read permission
                          -w:
                          It returns true if the given file has write permission
                          -x:
                          It returns true if the given file has execute permission
                          -T:
                          It returns true if the given file is a Text file
                          -B:
                          It returns true if the given file is a Binary file
                          Ex: file-existence.pl
                          #!/usr/bin/perl -w
                          #Program to check the given file exists or not
                          print "\n Enter a filename::";
                          chomp($fname=<STDIN>);
                          if(open(FH,"<$fname"))
                          {
                          print "$fname file exists\n";
                          close(FH);
                          }
                          else
                          {
                          print "\n $fname file doesn't exist\n";
                          }
                          Ex: file-existence1.pl
                          #!/usr/bin/perl -w
                          print "\n Enter a filename:";
                          chomp($fname=<STDIN>);
                          #die: Predefined function, used to terminate the program
                          #$!: It displays perl generated error message
                          die "cann't open a file. $!" unless(open(FH,"$fname"));
                          print "\n$fname file exists";
                          close(FH);
                          print "\n";
                          Ex: file-open.pl
                          #!/usr/bin/perl -w
                          #Program for opening a file
                          print "\n Enter a file name:";
                          chomp($fname=<STDIN>);
                          die "cann't open a file. $!" unless(open(FIN,"$fname"));
                          while($x=<FIN>)
                          {
                          print "$x";
                          }
                          close(FIN);
                          Ex: file-open1.pl
                          #!/usr/bin/perl -w
                          print "\n Enter a filename:";
                          chomp($fname=<STDIN>);
                          die "Can't open a file. $! unless(open(FH,"$fname"));
                          @x=<FIN>;
                          print "@x";
                          print "\n Total lines:",$#x+1;
                          close(FIN);
                          Ex: print-oddlines-from-file.pl
                          #!/usr/bin/perl -w
                          print "\nEnter a filename:";
                          chomp($fname=<STDIN>);
                          die "Cann't open a file.$!" unless(open(FIN,"$fname"));
                          $i=0;
                          while($x=<FIN>)
                          {
                          $i++;
                          next if($i%2==0);
                          print "$i.$x";
                          }
                          close(FIN);
                          Ex:
                          create-file.pl
                          #!/usr/bin/perl -w
                          print "\nEnter a filename to be created:";
                          chomp($fname=<STDIN>);
                          open(FOUT,">>$fname");
                          print "Enter data to the file and press ctl+d:";
                          while($x=<STDIN>)
                          {
                          print FOUT "$x";
                          }
                          print "**********$fname file created*********\n";
                          close(FOUT);
                          Ex: check-file-type.pl
                          #!/usr/bin/perl -w
                          print "\nEnter a file name:";
                          chomp($fname=<STDIN>);
                          if(-e $fname)
                          {
                          if(-f $fname)
                          {
                          print "\n $fname is a regular file\n";
                          }
                          elsif(-d $fname)
                          {
                          print "\n $fname is a directory\n";
                          }
                          }
                          else
                          {
                          print "\n$fname file doesn't exist\n";
                          }
                          Directory Handling
                          Directory is a collection of files
                          Directory Functions
                          opendir()
                          : It is used for to open directory
                          opendir(DIRHANDLE,"dirname");
                          ex: opendir(DH,"abc");
                          readdir():
                          It is used for to read files from given directory
                          readdir(DIRHANDLE);
                          ex: readdir(DH);
                          rewinddir():
                          It places pointer at the beginning of the given directory
                          rewinddir(DIRHANDLE);
                          ex: rewinddir(DH);
                          closedir():
                          It is used for to close the directory which is already opened
                          closedir(DIRHANDLE);
                          ex:closedir(DH);
                          mkdir():
                          To create a new directory
                          mkdir(dirname);
                          ex: mkdir("dirname");
                          chdir():
                          To change directory
                          chdir(dirname);
                          ex: chdir("abc");
                          rmdir():
                          To remove a directory
                          rmdir(dirname);
                          ex: rmdir("abc");
                          Ex:file-count.pl
                          #!/usr/bin/perl -w
                          #WAP to accept a directory and print all files and count no of file
                          print "\nEnter a directory name:";
                          chomp($dname=<STDIN>);
                          die "Can't open a directory. $!" unless(opendir(DH,"$dname"));
                          $cnt=0;
                          while($x=readdir(DH))
                          {
                          print "$x\n";
                          $cnt++;
                          }
                          print "\nTotal no of files in $dname directory: $cnt\n";
                          closedir(DH);
                          Ex:
                          dir-subdir-count.pl
                          #!/usr/bin/perl -w
                          #WAP to accept a directroy and count no of files and no of sub directories
                          print "\nEnter a directory name:";
                          chomp($dname=<STDIN>);
                          die "Can't open a directory. $!" unless(opendir(DH,"$dname"));
                          $fcnt=0;
                          $dcnt=0;
                          while($x=readdir(DH))
                          {
                          if(-f $x)
                          {
                          $fcnt++;
                          }
                          elsif(-d $x)
                          {
                          $dcnt++;
                          }
                          }
                          print "\nTotal no of files in $dname directory:$fcnt";
                          print "\nTotal no of subdirectories : $dcnt\n";
                          closedir(DH);

                          Ex: rem-directory.pl
                          #!/usr/bin/perl -w
                          #WAP to remove directory
                          print "\nEnter a dir name to remove:";
                          chomp($dname=<STDIN>);
                          rmdir($dname);
                          print "*******$dname directory has been deleted********\n";
                          Regular Expressions
                          Any string contains wild card character known as regular expression
                          Wild card characters: *, ., ?, [, ], -
                          t.*t à Regular expression
                          /t.*t/ à Pattern
                          The 2 binding operators are
                          =~ à It returns true if the given pattern found
                          !~ à It returns true if the given pattern not found
                          Wild card characters or Meta characters
                          1)* à It matches Zero or more occurrence of preceding character
                          2) + à It matches one or more occurrence of preceding character
                          3)? à It matches Zero or one occurrence of preceding character
                          4). à It matches any single character
                          5)[ ] à It matches any single character in the given list
                          6)[^] à It matches any single character other than in the given list
                          7)[-] à It matches any single character in the given range
                          8)(|) à It matches any one string in the list
                          9){m} à It matches exact occurrence of preceding character
                          10){m,n} à It matches min m occurrence and max n occurrence of its preceding character
                          11){m,} à It matches min m occurrence and max no limit of its preceding
                          12)^ à Start of the line
                          13)$ à End of the line
                          14)\d or [0-9] à Any single digit
                          [0-9] [0-9] [0-9] [0-9] or [0-9]{4} or \d\d\d\d or \d{4}
                          15)\D or [^0-9] à Any single non digit
                          16)\w or [a-zA-Z0-9_] à Any alphanumeric
                          17)\W or [^a-zA-Z0-9_] à Any non alphanumeric or special character
                          18)\s à ‘ ‘, ‘\t’, ‘\n’
                          19)\b à Word Boundary
                          Examples:
                          $str=~/perl/ à It searches the perl sting ( It will search character by character)
                          $str=~/\bperl/ à Word starting with perl
                          $str=~/perl\b/ à Word ending with perl
                          $str=~/^perl/ à Line starting with perl
                          $str=~/perl$/ à Line ending with perl
                          If($str=~/^perl$) à Line should contain only perl
                          If($str=~/^perl.*perl$/) à line starting with perl and line ending with perl
                          If($str=~/^$/) à blank lines
                          If($str=~/\b\d{4}\b/) à 4 digit number
                          If($str=~/\b\d{3,5}\b/) à searching 3 or 4 or 5 digit number
                          If($str=~/\b\w{3,5}\b/) à searching 3 or 4 or 5 digit character word
                          If($str=~/^\w+\s\w+\s\w+\s$/) à the line is having exactly 3 words
                          If($str=~/\b(2[6-9][34][0-9]5[0-5]\b/) à searching no b/w 26 to 55
                          If($str=~/\b\d{2}-\d{2}-\d{2}\b/) à 02-08-13
                          If($str=~/\b\d{2}-\d{2}-(\d{2}|\d{4}\b})\b/) à 02-08-13 or 02-08-2013
                          If($str=~m{\b\d{2}[-/]\d{2}[-/](\d[2]|\d{4})\b}) à 02-0-13 or 02-08-2-13 or 02/08/13 or 02/08/2013 or 02-05/13
                          If($str=~m{\b\d{2}([-/#])\d{2}/1(\d[2]|\d{4})\b}) à 02-0-13 or 02-08-2-13 or 02/08/13 or 02/08/2013 or 02/05/13
                          Substitution string by string
                          if($str=~s/Perl/linux/gi) à Every line all the occurrences
                          if($str=~s/^Perl/linux/gi) à Ever line first occurrence
                          if($str=~s/Perl//gi) à Replacing empty string
                          Translation character by character
                          If($str=~tr/a/t)
                          If($str=~tr/am/tp)
                          If($str=~tr/[a-z]/[A-Z]/)
                          PERL Predefined Functions
                          String Functions
                          1)ord():
                          It returns given character ASCII value
                          Print ord(‘a’); #97
                          Print ord(‘A’); #65
                          2)chr():
                          It returns given ASCII code character
                          Print chr(65); #A
                          Print chr(97); #a
                          3)uc():
                          It returns the given string in upper case
                          Print uc("pavan"); #PAVAN
                          4)lc():
                          It returns the given string in lower case
                          Print lc("PAVAN") #pavan
                          5)ucfirst():
                          It returns the given sting first character into upper case
                          Print ucfirst("pavan") #Pavan
                          6)lcfirst():
                          It returns the given string character into lower case
                          Print lcfirst("PAVAN") #pAVAN
                          7)length():
                          It returns the length of the given string
                          Print length("pavan") #5
                          8)substr("string,start,length) :
                          It extracts the specified portion from the string
                          Print substr("I like Perl",4,5); #ke pe
                          9) index(mainstring,substring):
                          It returns position of the substring in main string,
                          if substring not found in main string, it returns -1
                          print index("I like perl","perl"); #7
                          print index("I like perl","unix"); #-1
                          10) chop():
                          It deletes the given string last character
                          $str="I like perl";
                          chop($str);
                          print $str; #i like per
                          11) split():
                          It is used for to split the string into multiple values based on one or more delimiters.
                          $str="This is perl scripting class";
                          @x=split(" ",$str);
                          print "total elements:",$#x+1;
                          $str="This is,perl scripting:class";
                          @x=split(",| |:",$str);
                          Print "\n Total elements: ",$#x+1;
                          12) join():
                          It is used for to join multiple values into single string based on delimiter @num=(10,20,30,40,50,60);
                          $x=join(":",@num);
                          Print "$x"; #10:20:30:40:50:60
                          Array Functions:
                          1. push() :
                          it adds elements at end of the array
                          @x=(10,20,30,40);
                          Push(@x,50,60,70);
                          Print "@x"; # 10 20 30 40 50 60 70
                        6. unshift():
                        7. it adds elements at beginning of the array
                          @x=(10,20,30,40);
                          unshift(@x,50,60,70);
                          Print "@x"; 50 60 70 10 20 30 40
                        8. pop():
                        9. it returns and deletes last element from the array
                          @x=(10,20,30,40);
                          $k=pop(@x);
                          Print "The deleted element is : $k"; #40
                          Print "@x"; # 10 20 30
                        10. shift():
                        11. it returns and deletes first element from the array
                          @x=(10,20,30,40);
                          $k = shift(@x);
                          Print "The deleted element is : $k"; #10
                          Print "@x"; #20 30 40
                        12. sort():
                        13. it sorts given array elements in asc order
                          @x=qw(one two three four five);
                          @y=sort(@x);
                          Print "@y"; #five four one three two
                          Print "@x"; #one two three four five
                        14. reverse():
                        15. It returns elements last first from the given array
                          @x=qw(one two three four five);
                          @y=reverse(@x);
                          Print "@y"; #five four three two one
                          Print "@x"; #one two three four five
                          reverse(sort(@x));
                        16. splice():
                        17. It is used for to replace particular portion from the array or to append elements at end of the array
                          splice(@oldarray,start,length,@newarray)
                          @x=qw( a b c d e f);
                          @num=(1,2,3,4);
                          splice(@x,2,3,@num);
                          print "@x"; #a b 1 2 3 4 f
                          splice(@x,2,0,@num);
                          print "@x"; #a b 1 2 3 4 c d e f
                          splice(@x,2,3)
                          print "@x"; #a b f
                          Mathematical Functions
                          1. abs():
                          it returns absolute value
                          print abs(-45);#45
                        18. sqrt():
                        19. it returns square root of the given number
                          print sqrt(100); #10
                          print sqrt(abs(-100)); #10
                        20. rand:
                        21. it returns random number between 0 to 1
                        22. rand(n)
                        23. : it returns random number between 0 to n
                        24. sin(x):
                        25. it returns sin value
                        26. cos(x):
                        27. it returns cos value
                        28. tan(x):
                        29. it returns tan value
                        30. log(x):
                        31. it returns log value
                          Date and Time Functions
                          localtime():
                          it returns date and time
                          Sub Routines or User defined functions
                          Function is a group of statements to perform certain task and it must return a value. The main concept of function is to reduce length code of the program, easy to maintain, supports reusability, reduces cost of maintenance.
                          Syntax:
                          &functionname(arg1,arg2,……); ---- > Calling Function
                          -----------
                          -----------
                          -----------
                          -----------
                          Sub funcationname ---- > called function or defining function
                          {
                          -----------
                          -----------
                          -----------
                          -----------
                          }
                          @_ is a special variable; it holds all function call arguments
                          Example 1:
                          sub hello
                          {
                          print "\n , hello, good evening";
                          }
                          hello;
                          print "\n bye, have a nice day";
                          Example 2:
                          &hello; #forward reference
                          hello;
                          print "\n bye, have a nice day";
                          sub hello
                          {
                          Print "\n hello, good evening";
                          }
                          Example 3:
                          display("hello","good","evening");
                          sub display
                          {
                          Print "Total no of args:", $#_+1;
                          Print "\n @_";
                          }
                          Example 4:
                          sum(10,20,30);
                          sub sum
                          {
                          ($x,$y)=@_;
                          Print "\n sum=$n";
                          }
                          Example 5:
                          sum(10,20);
                          sub sum
                          {
                          $x=$_[0];
                          $y=$_[1];
                          $n=$x+$y;
                          Print "\n sum=$n";
                          }
                          Example 6:
                          sum(10,20);
                          sub sum
                          {
                          $x=shift(@_);
                          $y=shift(@_);
                          $n=$x+$y;
                          Print "\n sum =$n";
                          }
                          Example 7:
                          $n=&sum(10,20,30);
                          Print "\n sum1 = $n";
                          $n=$sum(10,20,30,40,50,60,70);
                          Print "\n sum2= &n";
                          sub sum
                          {
                          $total=0;
                          foreach $k (@_)
                          {
                          $total=$total+$k;
                          }
                          Return $total;
                          }
                          Example 8:
                          %days=("mon"=>1,"tue"=2,"wed"=>3,"thu"=>4,"fri"=>5);
                          &display(%days,"sat",6,"sun",7);
                          sub display
                          {
                          %h=@_;
                          while($x,$y)=each%h)
                          {
                          Print "\n $x week day no is : $y";
                          }
                          }
                          Example 9:
                          sub sum($\$); #prototype declaration
                          $a=10;
                          $b=20;
                          @x=(10,20,30,40,50);
                          sum($a,$b); #calling function
                          #sum($a); - wrong
                          #sum($a,$b,30,40); - wrong
                          #sum($a,@x); - wrong
                          sub sum($/$) # prototype declaration
                          {
                          $x=$_[0];
                          $y=$_[1];
                          $n=$x+$y;
                          print "\n sum=$n";
                          }

                          Scope of variables
                          1)our
                          2)my
                          3)local
                          The default scope is our scope.
                          The our scope variables can be accessed any where in the program
                          The my scope variables can be accessed within that block only.
                          The local scope variable can be accessed within that function and it child functions
                          Example 1:
                          $x=100;
                          &f1();
                          &f2();
                          Print "\n In main, x=$x, y=$y,z=$z"; # 110,empty,empty
                          sub f1
                          {
                          my $y=200;
                          local $z=300;
                          print "\n In f1, x=$x, y=$y,z=$z"; # 100,200,300
                          $x=$x+10;
                          &f3();
                          }
                          sub f3
                          {
                          print "\n In f3, x=$x, y=$y,z=$z"; # 110,empty,300
                          &f2();
                          }
                          sub f2
                          {
                          print "\n In f2, x=$x, y=$y,z=$z"; # 100,empty,empty
                          }
                          Example 2:
                          use strict; #It forces the user to declare variables explicitly
                          use warnings;
                          our $count=1;
                          our $x=10;
                          while($count<=3)
                          {
                          print "$x \n";
                          $x=$x+10;
                          $count=$count+1;
                          }

                          Command line arguments
                          At the time of execution of perl script, if user passes any arguments known as command line arguments. @ARGV is a special variable, it holds all command line argument values
                          Example 1:
                          #perl hello.pl pavan kumar Bangalore
                          print "\n Total no of Args:",$#ARGV+1;
                          Example 2:
                          #perl sum.pl 10 20
                          $n=@ARGV;
                          if($n= =2)
                          {
                          my($a,$b)=@ARGV;
                          my $c=$a+$b;
                          print "\n sum: $c";
                          }
                          else
                          {
                          print "\n Invalid Arguments";
                          }
                          Example 3:
                          #perl copy.pl sample.txt temp.txt
                          $n=@ARGV;
                          if($n= =2)
                          {
                          $src=$ARGV[0];
                          $tar=$ARGV[1];
                          die "can’t open a source file. $!" unless(open(FIN,"<$src"));
                          open(FOUT,">$tar");
                          while($str=<FIN>)
                          {
                          print FOUT "$str";
                          }
                          print "\n File copied successfully";
                          close(FIN);
                          close(FOUT);
                          }
                          else
                          {
                          Print "Invalid no of Arguments";
                          }
                          Modules:
                          Module is a collection of properties (variables, methods, functions)
                          1. pakage is a keyword to create a module

                          2. pakage name and module name must be same

                          3. extension of the perl module is .pm

                          4. the perl module must register in perl/site/lib directory

                          5. module must return a true value

                          6. main concept is reusability

                          7. use and require are the keywords to import perl modules

                          8. use keyword imports perl module properties and methods at compile time

                          9. require keyword imports perl modules and methods at runtime
                          How to access perl properties and methods
                          <Module name>::<Method name>
                          Or
                          <Module name>;
                          $object_name=new
                          $object_nameà Method name

                          Saturday, 22 June 2013

                          Log4J Levels

                          Five standard log4j levels

                          DEBUG Level

                          This log4j level helps developer to debug application. Level of message logged will be focused on providing support to a application developer.

                          INFO Level

                          This log4j level gives the progress and chosen state information. This level will be generally useful for end user. This level is one level higher than DEBUG.

                          WARN Level

                          This log4j level gives a warning about an unexpected event to the user. The messages coming out of this level may not halt the progress of the system.

                          ERROR Level

                          This log4j level gives information about a serious error which needs to be addressed and may result in unstable state. This level is one level higher than WARN.

                          FATAL Level

                          This log4j level is straightforward and you don’t get it quite often. Once you get this level and it indicates application death.

                          Two special log4j levels

                          ALL Level

                          This log4j level is used to turn on all levels of logging. Once this is configured and the levels are not considered.

                          OFF Level

                          This log4j level is opposite to ALL level. It turns off all the logging.

                          New Trace Level added in Log4j

                          TRACE Level

                          This log4j level gives more detailed information than the DEBUG level and sits top of the hierarchy. This level is introduced from version 1.2.12 in log4j.

                          Custom log4j levels

                          Log4j’s levels are mostly sufficient for all common applications. Rarely you may need a new Level apart from the levels provided by log4j. In that case you can extend org.apache.log4j.Level class and have your own custom level implementation.

                          Log4j Logger Output

                          When a logger is created, generally you assign a level. The logger outputs all those messages equal to that level and also all greater levels than it. So the order for the standard log4j levels are:

                          Log4J Levels

                          TRACE Level DEBUG Level INFO Level WARN Level ERROR Level FATAL Level
                          TRACE Level Y Y Y Y Y Y
                          DEBUG Level N Y Y Y Y Y
                          INFO Level N N Y Y Y Y
                          WARN Level N N N Y Y Y
                          ERROR Level N N N N Y Y
                          FATAL Level N N N N N Y
                          ALL Level Y Y Y Y Y Y
                          OFF Level N N N N N N

                          Log4j Level Inheritance Rule

                          There can be instances when you don’t assign a level to the logger. In such cases log4j handles it seamlessly based on the following level inheritance rule:
                          The inherited level for a given logger C, is equal to the first non-null level in the logger hierarchy, starting at C and proceeding upwards in the hierarchy towards the root logger.
                          That means, if you have a package as com.foo.bar and you didn’t allocate a level, then it will inherit the level from com.foo package. Still in that package also if the level is not available, then it will inherit from the log4j root level. The log4j’s root logger is instantiated and available always. Log4j’s root logger by default has DEBUG level.

                          Apache Redirects


                          Overview

                          What you are trying to accomplish here is to have one resource (either a page or an entire site) redirect a visitor to a completely different page or site, and while doing so tell the visitor's browser that the redirect is either permanent (301) or temporary (302).
                          Therefore you need to do three things:
                          1. Have 2 resources - one source page or website, and one destination page or website.
                          2. When an attempt to  access the source resource is made, the webserver transfers the visitor to the destination instead.
                          3. During the transfer, the webserver reports to the visitor that a redirect is happening and it's either temporary or permanent.
                          The ability to control the "status" argument in the redirect directive (which sets whether it's a 301 or 302) within Apache is only available in version 1.2 and above. You are best off using version 2 or above for maximum stability, security and usefulness. 

                          301 Redirect
                          A function of a web server that redirects the visitor from the current page or site to another page or site, while returning a response code that says that the original page or site has been permanently moved to the new location. Search engines like this information and will readily transfer link popularity (and PageRank) to the new site quickly and with few issues. They are also not as likely to cause issues with duplication filters. SEOs like 301 redirects, and they are usually the preferred way to deal with multiple domains pointing at one website.
                          302 Redirect
                          A function of a web server that redirects the visitor from the current page or site to another page or site, while returning a response code that says that the original page or site has been temporarily moved to the new location. Search engines will often interpret these as a park, and take their time figuring out how to handle the setup. Try to avoid a 302 redirect on your site if you can (unless it truly is only a temporary redirect), and never use them as some form of click tracking for your outgoing links, as they can result in a "website hijacking" under some circumstances.
                           
                          mod_rewrite
                          Mod_Rewrite is an Apache extension module which will allow URL's to be rewritten on the fly. Often this is used by SEOs to convert dynamic URL's with multiple query strings into static URL's. An example of this would be to convert the dynamic URL domain.com/search.php?day=31&month=may&year=2005 to domain.com/search-31-may-2005.htm
                           
                          htaccess
                          htaccess (Hypertext Access) is the default name of Apache's directory-level configuration file. It provides the ability to customize configuration directives defined in the main configuration file. You can execute a mod_rewrite script using the .htaccess file.
                           
                          httpd.conf
                          Apache is configured by placing directives in plain text configuration files. The main configuration file is usually called httpd.conf. The location of this file is set at compile-time, but may be overridden with the -f command line flag. In addition, other configuration files may be added using the Include directive, and wildcards can be used to include many configuration files. Any directive may be placed in any of these configuration files. Changes to the main configuration files are only recognized by Apache when it is started or restarted.

                          Redirection (302)
                          A default redirection function of IIS that redirects the visitor from the current page or site to another page or site, while returning a response code that says that the original page or site has been temporarily moved to the new location. Search engines will often interpret these as a park, and take their time figuring out how to handle the setup. Try to avoid a 302 redirect on your site if you can (unless it truly is only a temporary redirect), and never use them as some form of click tracking for your outgoing links, as they can result in a "website hijacking" under some circumstances.
                           
                           Permanent Redirection (301)
                          An optional function of IIS that redirects the visitor from the current page or site to another page or site, while returning a response code that says that the original page or site has been permanently moved to the new location. Search engines like this information and will readily transfer link popularity (and PageRank) to the new site quickly and with few issues. They are also not as likely to cause issues with duplication filters. SEOs like 301 redirects, and they are usually the preferred way to deal with multiple domains pointing at one website.

                          Mod_Rewrite and the Apache Redirect

                          If you have the mod_rewrite extension installed (it comes with most Apache installs as a default) you can use it to dynamically change URL's using arguments on the fly - this is NOT a 301 redirect, but rather it's related behavior. For example, if you wanted to redirect .htm files from an old server to their equivalent .php files on a new one using a 301 redirect, you would use a combination of mod_rewrite and the redirect directive to do the redirection + URL change.
                          You could do it on a file by file basis by making a really long list of possible redirects in the .htaccess file by hand without mod_rewrite, but that would be a real pain on a server with a lot of files, or a completely dynamic system. Therefore these 2 functions are often used together.

                          Syntax for a 301 Redirect

                          The syntax for the redirect directive is:
                          Redirect /yourdirectory http://www.newdomain.com/newdirectory
                          If the client requests http://myserver/service/foo.txt, it will be told to access http://www.yourdomain.com/service/foo.txt instead.
                          Note: Redirect directives take precedence over Alias and ScriptAlias directives, irrespective of their ordering in the configuration file. Also, URL-path must be a fully qualified URL, not a relative path, even when used with .htaccess files or inside of <Directory> sections.
                          If you use the redirect without the status argument, it will return a status code of 302 by default. This default behaviour has given me problems over the years as an SEO, so it's important to remember to use it, like this:
                          Redirect permanent /one http://www.newdomain.com/two
                          or
                          Redirect 301 /two http://www.newdomain.com/other
                          Both of which will return the 301 status code. If you wanted to return a 302 you could either not specify anything, or use "302" or "temp" as the status argument above.
                          You can also use 2 other directives - RedirectPermanent URL-path URL (returns a 301 and works the same as Redirect permanent /URL PathURL) and RedirectTemp URL-path URL (same, but for a 302 status).
                          For more global changes, you would use redirectMatch, with the same syntax:
                          RedirectMatch 301 ^(.*)$ http://www.newdomain.com
                          or
                          RedirectMatch permanent ^(.*)$ http://www.newdomain.com
                          These arguments will match any file requested at the old account, change the domain, and redirect it to the file of the same name at the new account.
                          You would use these directives in either the .htaccess file or the httpd file. It's most common to do it in the .htaccess file because it's the easiest and doesn't require a restart, but the httpd method has less overhead and works fine, as well.

                          Simple Domain 301 Redirect Checklist

                          This assumes you just have a new domain (with no working pages under it) and want it to redirect properly to your main domain.
                          1. Ensure that you have 2 accounts - the old site and the new site (they do not have to be on different IP's or different machines).
                          2. Your main (proper or canonical) site should be pointed at the new site using DNS. All your other domains should be pointed at the old site using DNS. Parking them there is fine at this point.
                          3. Find the .htaccess file at the root of your old account. Yes, it starts with a "." We will be working with this file. The new site does not need any changes made to it - the old site does all the redirection work.
                          4. Download the .htaccess file and open it in a text only editor.
                          5a. Add this code:
                          Redirect 301 / http://www.newdomain.com/
                          6. Then upload the file to your root folder and test your new redirect. Make you you also check it using a HTTP Header viewer just to be sure it shows as a 301.

                          Control Panel Method

                          cPanel redirect

                          • Log into your cPanel, and look for "Redirects" under Site Management
                          • Put in the current directory into the first box
                          • Put the new directory in the second box
                          • Choose the type (temporary or permanent) temporary=302 and permanent=301
                          • Click "Add" and you're done
                          You can only do 302 redirects (or frame forwarding - bad!) using the Plesk control panel - use .htaccess for 301's instead.
                          If you use Ensim, the only way to redirect is by using the .htaccess file (no control panel option at this time).

                          Basic Old Website to New Website Redirection

                          This is used when you have an existing website (with pages) and want to move it to a new domain, while keeping all your page names and the links to them.
                          1. Ensure that you have 2 websites - the old site and the new site, and that they are on different accounts (they do not have to be on different IP's or different machines).
                          2. Your main (proper or canonical) site should be pointed at the new site using DNS. All your old domains should be pointed at the old site using DNS.
                          3. Find the .htaccess file at the root of your old account. Yes, it starts with a "."  We will be working with this file. The new site does not need any changes made to it - the old site does all the redirection work.
                          4. Download the .htaccess file and open it in a text only editor.
                          5a. If you have mod_rewrite installed, add this code:
                          Options +FollowSymLinks
                          RewriteEngine on
                          RewriteCond %{HTTP_HOST} !^newdomain\.com
                          RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]
                          5b. If you don't have mod_rewrite installed, you really should. If you can't install it, then you can use this code instead:
                          RedirectMatch 301 ^(.*)$ http://www.newdomain.com
                          6. Then upload the file to your root folder and test your new redirect. Make you you also check it using a HTTP Header viewer just to be sure it shows as a 301.

                          FrontPage on Apache

                          After you've done the basic Apache 301 redirection described in this article, you will also need to change the .htaccess files in:  
                          _vti_bin
                          _vti_bin /_vti_adm
                          _vti_bin/ _vti_aut
                          Replace "Options None" to "Options +FollowSymLinks"
                          Those folders are part of your FrontPage extensions on the server, so you will have to use FTP to get to them, since FrontPage hides these folders by default to prevent them from accidentally being messed with by novice users.

                          More Complicated Redirects

                          You can't use a control panel in Apache currently for these - .htaccess only.

                          Redirecting everything to a single page

                          This is common when you are totally changing the new website from the old and you just want all your links and requests form the old site to be directed to a spot on your new site (usually the home page). You actually need to do it on a page by page basis.
                          Redirect 301 /oldfile1.htm http://www.newdomain.com
                          Redirect 301 /oldfile2.htm http://www.newdomain.com
                          Redirect 301 /oldfile3.htm http://www.newdomain.com

                          Redirection while changing the filename

                          This example will redirect all the files on the old account that end in html to the same file on the new account, but with a php extension. You can also use this technique within the same account if you want to change all your extensions but don't want to lose your incoming links to the old pages. This is common when people switch to from static htm files to dynamic ones while keeping the same domain name, for example.
                          Just change the "html" and "php" parts of the below example to your specific situation, if needed.
                          RedirectMatch 301 (.*)\.html$ http://www.newdomain.com$1.php

                          Redirection while changing the filename, but keeping the GET arguments

                          Sometimes, you will want to change to a different CMS, but keep your database the same, or you want to switch everything but you like the arguments and don't want to change them.
                          RedirectMatch 301 /oldcart.php(.*) http://www.newdomain.com/newcart.php$1
                          This will result in "http://www.olddomain.com/oldcart.php?Cat_ID=Blue" being redirected to "http://www.newdomain.com/newcart.php?Cat_ID=Blue"

                          .htaccess Error Documents


                          In Apache, you can set up each directory on your server individually, giving them different properties or requirements for access. And while you can do this through normal Apache configuration, some hosts may wish to give users the ability to set up their own virtual server how they like. And so we have .htaccess files, a way to set Apache directives on a directory by directory basis without the need for direct server access, and without being able to affect other directories on the same server.

                          One up-side of this (amongst many) is that with a few short lines in an .htaccess file, you can tell your server that, for example, when a user asks for a page that doesn't exist, they are shown a customized error page instead of the bog-standard error page they've seen a million times before. If you visit http://www.addedbytes.com/random_made_up_address then you'll see this in action - instead of your browser's default error page, you see an error page sent by my server to you, telling you that the page you asked for doesn't exist.

                          This has a fair few uses. For example, my 404 (page not found) error page also sends me an email whenever somebody ends up there, telling me which page they were trying to find, and where they came from to find it - hopefully, this will help me to fix broken links without needing to trawl through mind-numbing error logs.

                          [Aside: If you set up your custom error page to email you whenever a page isn't found, remember that "/favicon.ico" requests failing doesn't mean that a page is missing. Internet Explorer 5 assumes everyone has a "favicon" and so asks the server for it. It's best to filter error messages about missing "/favicon.ico" files from your error logging, if you plan to do any.]

                          Setting up your htaccess file is a piece of cake. First things first, open notepad (or better yet, [url=http://www.editplus.com/]EditPlus2[/url]), and add the following to a new document:
                          ErrorDocument 404     /404.html

                          Next you need to save the file. You need to save it as ".htaccess". Not ".htaccess.txt", or "mysite.htaccess" - just ".htaccess". I know it sounds strange, but that is what these files are - just .htaccess files. Nothing else. Happy? If not, take a look at this [url=http://wsabstract.com/howto/htaccess.shtml].htaccess guide[/url], which also explains the naming convention of .htaccess in a little more depth. If you do use Notepad, you may need to rename the file after saving it, and you can do this before or after uploading the file to your server.

                          Now, create a page called 404.html, containing whatever you want a visitor to your site to see when they try to visit a page that doesn't exist. Now, upload both to your website, and type in a random, made-up address. You should, with any luck, see your custom error page instead of the traditional "Page Not Found" error message. If you do not see that, then there is a good chance your server does not support .htaccess, or it has been disabled. I suggest the next thing you do is check quickly with your server administrator that you are allowed to use .htaccess to serve custom error pages.

                          If all went well, and you are now viewing a custom 404 (page not found) error page, then you are well on your way to a complete set of error documents to match your web site. There are more errors out there, you know, not just missing pages. Of course, you can also use PHP, ASP or CFML pages as error documents - very useful for keeping track of errors.

                          You can customize these directives a great deal. For example, you can add directives for any of the status codes below, to show custom pages for any error the server may report. You can also, if you want, specify a full URL instead of a relative one. And if you are truly adventurous, you could even use pure HTML in the .htaccess file to be displayed in case of an error, as below. Note that if you want to use HTML, you must start the HTML with a quotation mark, however you should not put one at the other end of the HTML (you can include quotation marks within the HTML itself as normal).
                          ErrorDocument 404 "Ooops, that page was <b>not found</b>. Please try a different one or <a href="mailto:owner@site.com">email the site owner</a> for assistance.
                          Server response codes

                          A server reponse code is a three digit number sent by a server to a user in response to a request for a web page or document. They tell the user whether the request can be completed, or if the server needs more information, or if the server cannot complete the request. Usually, these codes are sent 'silently' - so you never see them, as a user - however, there are some common ones that you may wish to set up error pages for, and they are listed below. Most people will only ever need to set up error pages for server codes 400, 401, 403, 404 and 500, and you would be wise to always have an error document for 404 errors at the very least.

                          It is also relatively important to ensure that any error page is over 512 bytes in size. Internet Explorer 5, when sent an error page of less than 512 bytes, will display its own default error document instead of your one. Feel free to use padding if this is an issue - personally, I'm not going to increase the size of a page because Internet Explorer 5 doesn't behave well.

                          In order to set up an error page for any other error codes, you simply add more lines to your .htaccess file. If you wanted to have error pages for the above five errors, your .htaccess file might look something like this:
                          ErrorDocument 400     /400.html
                          ErrorDocument 401     /401.html
                          ErrorDocument 403     /403.html
                          ErrorDocument 404     /404.html 
                          ErrorDocument 500     /500.html

                          HTTP Status Codes

                          Informational
                              100 - Continue
                              A status code of 100 indicates that (usually the first) part of a request has been received without any problems, and that the rest of the request should now be sent.
                              101 - Switching Protocols
                              HTTP 1.1 is just one type of protocol for transferring data on the web, and a status code of 101 indicates that the server is changing to the protocol it defines in the "Upgrade" header it returns to the client. For example, when requesting a page, a browser might receive a statis code of 101, followed by an "Upgrade" header showing that the server is changing to a different version of HTTP.

                          Successful

                              200 - OK
                              The 200 status code is by far the most common returned. It means, simply, that the request was received and understood and is being processed.
                              201 - Created
                              A 201 status code indicates that a request was successful and as a result, a resource has been created (for example a new page).
                              202 - Accepted
                              The status code 202 indicates that server has received and understood the request, and that it has been accepted for processing, although it may not be processed immediately.
                              203 - Non-Authoritative Information
                              A 203 status code means that the request was received and understood, and that information sent back about the response is from a third party, rather than the original server. This is virtually identical in meaning to a 200 status code.
                              204 - No Content
                              The 204 status code means that the request was received and understood, but that there is no need to send any data back.
                              205 - Reset Content
                              The 205 status code is a request from the server to the client to reset the document from which the original request was sent. For example, if a user fills out a form, and submits it, a status code of 205 means the server is asking the browser to clear the form.
                              206 - Partial Content
                              A status code of 206 is a response to a request for part of a document. This is used by advanced caching tools, when a user agent requests only a small part of a page, and just that section is returned.

                          Redirection

                              300 - Multiple Choices
                              The 300 status code indicates that a resource has moved. The response will also include a list of locations from which the user agent can select the most appropriate.
                              301 - Moved Permanently
                              A status code of 301 tells a client that the resource they asked for has permanently moved to a new location. The response should also include this location. It tells the client to use the new URL the next time it wants to fetch the same resource.
                              302 - Found
                              A status code of 302 tells a client that the resource they asked for has temporarily moved to a new location. The response should also include this location. It tells the client that it should carry on using the same URL to access this resource.
                              303 - See Other
                              A 303 status code indicates that the response to the request can be found at the specified URL, and should be retrieved from there. It does not mean that something has moved - it is simply specifying the address at which the response to the request can be found.
                              304 - Not Modified
                              The 304 status code is sent in response to a request (for a document) that asked for the document only if it was newer than the one the client already had. Normally, when a document is cached, the date it was cached is stored. The next time the document is viewed, the client asks the server if the document has changed. If not, the client just reloads the document from the cache.
                              305 - Use Proxy
                              A 305 status code tells the client that the requested resource has to be reached through a proxy, which will be specified in the response.
                              307 - Temporary Redirect
                              307 is the status code that is sent when a document is temporarily available at a different URL, which is also returned. There is very little difference between a 302 status code and a 307 status code. 307 was created as another, less ambiguous, version of the 302 status code.

                          Client Error

                              400 - Bad Request
                              A status code of 400 indicates that the server did not understand the request due to bad syntax.
                              401 - Unauthorized
                              A 401 status code indicates that before a resource can be accessed, the client must be authorised by the server.
                              402 - Payment Required
                              The 402 status code is not currently in use, being listed as "reserved for future use".
                              403 - Forbidden
                              A 403 status code indicates that the client cannot access the requested resource. That might mean that the wrong username and password were sent in the request, or that the permissions on the server do not allow what was being asked.
                              404 - Not Found
                              The best known of them all, the 404 status code indicates that the requested resource was not found at the URL given, and the server has no idea how long for.
                              405 - Method Not Allowed
                              A 405 status code is returned when the client has tried to use a request method that the server does not allow. Request methods that are allowed should be sent with the response (common request methods are POST and GET).
                              406 - Not Acceptable
                              The 406 status code means that, although the server understood and processed the request, the response is of a form the client cannot understand. A client sends, as part of a request, headers indicating what types of data it can use, and a 406 error is returned when the response is of a type not i that list.
                              407 - Proxy Authentication Required
                              The 407 status code is very similar to the 401 status code, and means that the client must be authorised by the proxy before the request can proceed.
                              408 - Request Timeout
                              A 408 status code means that the client did not produce a request quickly enough. A server is set to only wait a certain amount of time for responses from clients, and a 408 status code indicates that time has passed.
                              409 - Conflict
                              A 409 status code indicates that the server was unable to complete the request, often because a file would need to be editted, created or deleted, and that file cannot be editted, created or deleted.
                              410 - Gone
                              A 410 status code is the 404's lesser known cousin. It indicates that a resource has permanently gone (a 404 status code gives no indication if a resource has gine permanently or temporarily), and no new address is known for it.
                              411 - Length Required
                              The 411 status code occurs when a server refuses to process a request because a content length was not specified.
                              412 - Precondition Failed
                              A 412 status code indicates that one of the conditions the request was made under has failed.
                              413 - Request Entity Too Large
                              The 413 status code indicates that the request was larger than the server is able to handle, either due to physical constraints or to settings. Usually, this occurs when a file is sent using the POST method from a form, and the file is larger than the maximum size allowed in the server settings.
                              414 - Request-URI Too Long
                              The 414 status code indicates the the URL requested by the client was longer than it can process.
                              415 - Unsupported Media Type
                              A 415 status code is returned by a server to indicate that part of the request was in an unsupported format.
                              416 - Requested Range Not Satisfiable
                              A 416 status code indicates that the server was unable to fulfill the request. This may be, for example, because the client asked for the 800th-900th bytes of a document, but the document was only 200 bytes long.
                              417 - Expectation Failed
                              The 417 status code means that the server was unable to properly complete the request. One of the headers sent to the server, the "Expect" header, indicated an expectation the server could not meet.

                          Server Error

                              500 - Internal Server Error
                              A 500 status code (all too often seen by Perl programmers) indicates that the server encountered something it didn't expect and was unable to complete the request.
                              501 - Not Implemented
                              The 501 status code indicates that the server does not support all that is needed for the request to be completed.
                              502 - Bad Gateway
                              A 502 status code indicates that a server, while acting as a proxy, received a response from a server further upstream that it judged invalid.
                              503 - Service Unavailable
                              A 503 status code is most often seen on extremely busy servers, and it indicates that the server was unable to complete the request due to a server overload.
                              504 - Gateway Timeout
                              A 504 status code is returned when a server acting as a proxy has waited too long for a response from a server further upstream.
                              505 - HTTP Version Not Supported
                              A 505 status code is returned when the HTTP version indicated in the request is no supported. The response should indicate which HTTP versions are supported.