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

Saturday, January 10, 2015

File Handling in Perl


Keyboard is considered as a file in most OS
<STDIN> is the file handle used to read from the keyboard
when we use STDIN in <>(angular) brackets it will return the file pointer or file handler using which we can read the contents from the Keyboard

A very simple example

    eg : print "Enter your name";
         $name = <STDIN>; # Read from the keyboard
         print "Good Morning, $name..!! \n";
       
         When you execute the program you will notice that it will print two new lines
         //$name will also contain the new line character
       
Chop function
---------------
This will remove the last character of whatever is given to it.

So we can rewrite the above program as
    print "Enter your name";
    chop($name = <STDIN>);
    print "Good Morning, $name..!! \n";

    This time the program will only print one new line char which is given in the program
    But remenber chopping sometimes might not be good, becuse it blindly removes the last char irrespective of what it is
   
Chomp Function
----------------
The chomp functions similar to the chop, witha difference that it chops of the last char only if it is a new line char
       
    print "Enter your name";
    chomp($name = <STDIN>);
    print "Good Morning, $name..!! \n";
   
Opening a File in Perl
-----------------------

The open command opens the file and return the file handle

For standard input we had a predefined file handle <STDIN>

    eg : $file = "/home/bin/report.txt";
         open XYZ, $file;
         while(<XYZ>) {
         print "Line number $. is $_";
         }
       
         Difference between XYZ and <XYZ> is , XYZ represents the file and <XYZ> represents the contents of the file
       
         $. is the line number
         $_ is the present line which is being read
       
         Sometimes file name may be wrong, or file may not exist, to handle that we use the following construct
       
         $file = "/home/bin/report.txt";
         open XYZ, $file or die "Error in open: $!"
         while(<XYZ>) {
         print "Line number $. is $_";
         }
       
         $! returns the error code or message
       
Reading from the file in Perl
-------------------------------

The <> is the line input operator, all the data read goes into $_

Writing into a file in Perl
----------------------------

    Eg : $out = "/home/bin/out.txt";
         open XYZ, ">$out" or die "Error in Write : $!" ;
         for $i (1..20) {
         print XYZ "$i :: Hello the time is scalar(localtime) \n";
         }
       
         Here ">$out" open the file given in the path
         print XYZ, will write the output to the file and not on the screen
         scalar(localtime) is the function in perl which returns the system time.
       
Appending the file
-------------------

        Eg : $out = "/home/bin/out.txt";
         open XYZ, ">>$out" or die "Error in Write : $!" ;
         for $i (1..20) {
         print XYZ "$i :: Hello the time is scalar(localtime) \n";
         }
       
        Here ">>$out" will open the file for appending
       
Print the file in Perl
------------------------
Print the contents of Perl is very easy

    eg : $out = "/home/bin/out.txt";
         open IN $input or die "Error in opening : $!";
         while(<IN>){
         print;         //By defaults print $_
         }
         close IN;
       
Command line args in Perl
--------------------------

Perl uses special array called @ARGV

List of arguments passed in the command line along with the scipt name will be stored in @ARGV

    eg : If ou invoke perl as
        perl test.pl red blue green
       
        then @ARGV wil be red blue green
       
        printing the command line arguments
       
        foreach(@ARGV) {
        print "$_";
        }
       
Difference between @ARGV and <ARGV>
--------------------------------------

@ARGV will contain the text after the scrpt nam efrom thr command line
<ARGV> will assume that each element after the script name is a name of the file
If no file name is given and <ARGV is used then by default it starts reading from the default input it keyboard

Consider an example
    This program will print the contents of the file you are passing
   
    eg : $lineno = 1;
         while(<>) {
            print $lineno++;
            print ":$_";
         }
       
         perl list_lines.pl file1.txt //contents of the file file1.txt will be printed
         perl list_lines.pl a.txt b.txt c.txt //contents of all the three files
       

       
       

       
   
       
       

Friday, December 19, 2014

What is the difference between $_ and @_ variables in Perl?

Both $_ and @_ are global variables.

In a subroutine, the array @_ pass the arguments to the given subroutine
Consider the example below,

sub print
{
foreach my $arg(@_) // @_ contains, abc, xyz, lmn, It collects from call and keeps them during execution
{
print "To Print =>$arg\n";
}
}

print('abc','xyz','lmn');

Output :
To Print =>abc
To Print =>xyz
To Print =>lmn

$_ is used as a variable for the loop

foreach(1..5)
{
  print "$_\n";
}

Output
1
2
3
4
5

Combining both the features

sub print
{
  foreach(@_)
  {
    print "You passed in $_ \n";
  }
}

print('abc','xyz','1','2','true');

Monday, December 15, 2014

Perl - How to Connect to DB and Perform Insert, Update, Delete, Commit, Rollback and other some other DBI functions



DBI stands for Database Independent Interface for Perl which means DBI provides an abstraction layer between the Perl code and the underlying database, allowing you to switch database implementations really easily.

The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used.

How to Conect to DB with Perl
------------------------------

#!/usr/bin/perl

use DBI
use strict;

my $driver = "mysql";
my $database = "TestDataBase";
my $dsn = "DBI:$driver:database=$database";
my $userid = "scott";
my $password = "tiger";

my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;

If the Database connection is successful then connect will return DBI handler for futher use.
Else returns the error errstr

How to insert record in to DB with Perl
------------------------------------------

my $sth = $dbh->prepare("INSERT INTO emp
                       (FIRST_NAME, LAST_NAME, SAL )
                        values
                       ('scott', 'james', 100)"); //Prepare the sql statement
$sth->execute() or die $DBI::errstr; //Execute the statement if successful continue else return errstr
$sth->finish(); //Release the connection
$dbh->commit or die $DBI::errstr; //Commit the changes done

or

$sth = $dbh->prepare(qq{
       INSERT INTO TEST_TABLE (FIRST_NAME, AGE) VALUES (?, ?)
       });
 $sth->execute("Joe", undef);

How to insert record and pass values during runtime
----------------------------------------------------

my $first_name = "john";
my $last_name = "poul";
my $SAL = 200
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
                       (FIRST_NAME, LAST_NAME, SAL )
                        values
                       (?,?,?)");
$sth->execute($first_name,$last_name,$sal)
          or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;

How to select rows from DB using Perl
---------------------------------------

my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME
                        FROM emp
                        WHERE AGE > 30");
$sth->execute() or die $DBI::errstr;

print "Number of rows found :" + $sth->rows;
while (my @row = $sth->fetchrow_array()) {
   my ($first_name, $last_name ) = @row;
   print "First Name = $first_name, Last Name = $last_name\n";
}
$sth->finish();

How to update DB records using Perl
------------------------------------

my $sth = $dbh->prepare("UPDATE TEST_TABLE
                        SET   AGE = AGE + 1
                        WHERE SAL > 200");
$sth->execute() or die $DBI::errstr;

print "Number of rows updated :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr

How to delete DB records using Perl
-------------------------------------

$age = 30;
my $sth = $dbh->prepare("DELETE FROM TEST_TABLE
                        WHERE AGE = ?");
$sth->execute( $age ) or die $DBI::errstr;

print "Number of rows deleted :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr

Get metadata from DB using Perl
--------------------------------
This will fetch available drivers

@ary = DBI->available_drivers;
@ary = DBI->available_drivers($quiet);

get all data sources
@ary = DBI->data_sources($driver);