Tuesday, July 25, 2017

Perl - Connect to Oracle database and SELECT

How to connect to a database from a Perl program? Let us see in this article how to connect to Oracle and read from a table.  As a pre-requisite, we need to have the DBI and DBD::Oracle packages installed.
   In this article, we are going to see how to read name of a student from the students table.

Example 1:
#!/usr/bin/perl 
use warnings ;
use strict ;
use DBI;

$\="\n";

print "Connecting to DB..";

my $dbh = DBI->connect('dbi:Oracle:xe',  'scott', 'tiger') or
          die "Cannot connect to DB => " . DBI->errstr;
my $sth = $dbh->prepare("select first_name, last_name from students where id = 10000") or
          die "Couldn't prepare statement: " . $dbh->errstr;
$sth->execute();

while (my ($f_name, $l_name) = $sth->fetchrow_array()){
    printf "First Name : %-10s Last Name : %-20s\n" , $f_name,  $l_name;
}
#$sth->finish();
$dbh->disconnect();


The above program when run will print the First Name and last name of the student whose id is 10000.

Wednesday, January 11, 2017

grep vs awk - Part 2

In this article, we will see more awk alternatives for the frequently used grep commands. This is in continuation to the grep vs awk - Part 1. Let us consider a sample file as shown below:
$ cat file
Unix

Linux
Uniix
Solaris
AIX
ArchLinux
Ubuntu
1. Search for a pattern present in a variable
$ x="Linux"
$ grep "$x" file
Linux
The variable x contains the search pattern. Using grep, the variable can directly be used.
$ awk -v var="$x" '$0 ~ var' file
Linux
In awk, the variable cannot be used directly. It needs to be passed to awk from shell using the -v option. More about the variable passing to awk.

Wednesday, January 4, 2017

How to use arrays in ksh?

  Array, as in any programming language, is a collection of elements. These elements need not be of the same type. One important difference here is shells support only one-dimensional arrays.

1. Creating an array:
   Creating an array is pretty simple.
$ typeset -a arr
$ arr[0]=25
$ arr[1]=18
$ arr[2]="hello"
 Using the typeset command, we let the shell know that we are intending to use the variable arr to store a list of elements. The -a indicates arr as an indexed array. Then the elements are assigned one by one using their index positions. Array indexing always starts from 0.