Wednesday, August 29, 2012

How could you convert a flat file to XML in Perl?

#!/usr/bin/perl

if ($#ARGV < 0)
{
 print "Usage : $0 <FlatFile Name>\n";
 exit;
}

my $in_txt=shift @ARGV;
my $out_xml=$in_txt;
$out_xml=~s/\.txt/\.xml/g;

open(INFO,"<$in_txt");
open(XML,">$out_xml");

print XML "<\?xml version=\"1.0\" encoding=\"UTF-16\"\?>\n";
print XML "<employee>\n";
while(<INFO>)
{
 if (/\A(.*?),(\d*+),(.*?),(\d*+),(\d*-\d*-\d+)/is)
 {
  print XML "<Employee_Detail>\n\t<Name>$1<\/Name>\n\t<Id>$2<\/Id>\n\t<State>$3<\/State>\n\t<Extension>$4<\/Extension>\n\t<Mobile>$5<\/Mobile>\n<\/Employee_Detail>\n";
 }
}
print XML "<\/employee>";
print "\"$in_txt\" got successfully converted to \"$out_xml\"";

employee.txt - The Flat File
------------------------------------------------------------------
Rabindra Nayak,23371,New Jercy,2370,212-555-6868
Mark Perino,23750,New York,2459,212-555-7979
Adam Gill,18654,DC,3897,212-555-5757
Tim Anderson,23456,Virginia,6543,212-555-3030
Mike Gotham,22500,Phoenix,7856,212-555-8989

Tuesday, August 28, 2012

Write a shell script to print itself.

#!/bin/sh

cat $0

How do you kill a process tree in UNIX?

Sometimes processes tend to re-spawn after being killed even if the parent process is killed.
The command below will kill all of the process (e.g. httpd process) :

ps -ef | grep httpd | awk '{print $2}' | xargs kill -9

How do you create temporary tables in Oracle?

Oracle database allows us to create Temporary tables of two types:

1- Transaction Specific Temporary Table
2- Session Specific Temporary Table

A transaction specific temporary table holds data when a transaction begins with execution of first SQL statement and ends either by commit or rollback. The following command creates a transaction specific temporary table.

CREATE global TEMPORARY TABLE temp_table
  (
     emp_id   NUMBER,
     emp_name VARCHAR2(50)
  )
ON COMMIT DELETE ROWS;


Note :- If "ON COMMIT" clause is omitted, by default oracle creates a transaction specific temporary table.

A session specific temporary table holds data until session lasts. When a commit is performed on session specific temporary table, data is preserved in table. But the data is not visible to others session. The data is lost when session ends.

Session specific temporary table can be created using “PRESERVE ROWS” in ON COMMIT clause.

CREATE global TEMPORARY TABLE temp_table
  (
     emp_id   NUMBER,
     emp_name VARCHAR2(50)
  )
ON COMMIT preserve ROWS;


The definition of temporary table is visible to all the sessions. Unlike permanent table, segment for temporary table is allocated when first INSERT statement is executed on temporary table. Indexes can also be created on temporary tables. The scope and life time of these indexes is similar to temporary tables.

Monday, August 27, 2012

How do you create temp tables in Sybase?

You can create Sybase temp tables in 2 ways :

1. CREATE TABLE #TableName
2. CREATE TABLE tempdb..TableName

Temp table being created with "#" are accessible by the current session or procedure and the table gets  automatically dropped when the session/procedure ends or is dropped manually.

Table being created using "tempdb..TableName" resides in tempdb database and remains as long as not dropped in manually. It is shareable among all sessions.

** If a table is created in any database other than tempdb, it won't be a temp table.

How could you determine the directory a shell script is in?

#!/usr/bin/sh -f

_DIR=`dirname "$(readlink -f $0)"`
echo ${_DIR}

Write a self-terminating shell script which doesn't hang up indefinately.

#!/usr/bin/sh

( sleep 5 ; echo Warning $0 hanging - aborted ; kill -9 $$ ) &
TIMEOUT_PID=$!

Your_Line1 ...
Your_Line2 ...
Your_Line3 ...
Your_Line4 ...
Your_Line5 ... 

# kill supervision sub-process
kill -9 $TIMEOUT_PID

How do you get 2nd, 3rd column of 2nd, 3rd row of CSV file?


head -3  <FileName> | tail -2 | cut -d "," -f 2-3
or
cat <FileName> | sed -n '2,3p' | cut -d "," -f 2-3
or
cat <FileName> | awk 'NR==2,NR==3' | cut -d "," -f 2-3

How could you read a file line by line in UNIX?

#!/usr/bin/sh

for line in $(cat <FileName>)
do
    echo "$line"
done

or

#!/bin/sh

file="<FileName>"

while read line
do
    echo $line
done < $file

Wednesday, August 22, 2012

How could you retrieve the manager's name of an employee within the EMPLOYEE table?

SELECT E.EMP_ID   AS EMPLOYEE_ID,
       E.EMP_NAME AS EMPLOYEE_NM,
       M.EMP_NAME AS MNGR_NM
FROM   EMP_MNGR E
       LEFT OUTER JOIN EMP_MNGR M
                    ON E.MNGR_ID = M.EMP_ID
ORDER  BY E.EMP_ID;


And the EMPLOYEE table goes as below :
EMP_ID    EMP_NAME    MNGR_ID
1001    Roger Scott   
2500    Mike Larsen    1001
2538    Marry Gartner  2500
2567    David Rice     2538
2570    Ben Tenesion   2567
2590    Joseph Robert  2570
3000    Adam McNally   1001

Tuesday, August 21, 2012

How can you execute the shell script currently editing within the VI editor?

You can execute the script from within the vi editor by using
:!%
where '%' refers to the file that you are currently editing.

How do you locate the source of a command/executable in UNIX?

Try - which or whereis or whence

For Example:
which perl
or
whereis perl
or
whence $0 (Korn Shell)

How could you debug specific lines in shell script intelligently?

We can implement an intelligent DEBUG-function to debug a script at specified line by putting the following function at the beginning of the script:

_DEBUG="on"
function DEBUG()
{
 [ "$_DEBUG" == "on" ] &&  $@
}

When done with debugging  or before moving your script to production, set "_DEBUG" to 'off'.
 _DEBUG="off"  # set to anything but not to 'on'

For Example:

#!/bin/bash

_DEBUG="on"
function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@
}

DEBUG echo 'Hi!'

How do you convert all cvs files to text or change the extension of all files?

#!/bin/sh

for FILE in *.cvs
do
 #Strip off extension
 FNAME=`echo $FILE | awk -F . '{ print $1 }'`
 mv $FILE ${FNAME}.txt
done

How do you get last command-line parameter passed to shell script?

#!/bin/sh

echo "${!#}"

How do you rename all the files in a directory at terminal?

for FILE in *; do mv $FILE $FILE.bkp; done
or
ls *.* | xargs -i mv \{\} \{\}.bkp

Monday, August 13, 2012

How do you get/print last field of every input line in UNIX?

sed -e 's/^.* //' <File Name>
or
awk '{ print $NF }' <File Name>

How do you implement auto-login FTP process in Perl via a proxy (.netrc)?

#!/usr/bin/perl -w

use Net::FTP;
use Net::Netrc;
use Logger::Simple;

# Declare and Define values for variables
my $logfile="/home/logs/$0.log";
my $log=Logger::Simple->new(LOG=>$logfile);

# Get the login info from the .netrc file located in HOME directory
my $RemoteHost=Net::Netrc->lookup('<Server Name>');
my $User=$NT->login;
my $Pass=$NT->password;

# Craete the FTP object
my $ftp=new Net::FTP($RemoteHost, Debug => 1);

# Log into Server and list files
if(! $ftp->login($User,$Pass) )
{
  $log->write("Unable to connect to $RemoteHost!");
  die $ftp->message;
}
else
{
  $log->write("Successfully Connected to $RemoteHost");
  $ftp->ascii();
  $ftp->cwd("/HOME/nayakr/project/perl");
  @list=$ftp->ls('-lart');
  $ftp->close();
}
foreach (@list)
{
        print $_;
}

Wednesday, August 8, 2012

How could you display the last line of a file in UNIX?

tail -1 <File Name>
or
sed '$!d' <File Name>
or
awk 'END{print $0}' <File Name>

What is the difference between 'MV' and 'CP' command?

mv :
- used to rename a file or move a file from one location to other.
- doesn't change timestamp.
- works like Cut+Paste.

cp :
- used to copy a file or create a duplicate of a file
- modifies the timestamp.
- works like Copy+Paste.

How could you read/display the nth line of a file?

head -n <File Name> | tail -1
or
sed 'nq;d' <File Name>
or
awk 'NR==<Line No.> { print $0; exit }' <File Name>

How do you set variable accessible form sub shells?

This can be achieved by using "export" command. It marks the variable for automatic export to the environment of subsequently executed commands i.e. makes the local shell variable global or environmental. For example :

export PATH=$PATH:/usr/local/bin

will make PATH variable global.

To see the list of all exported variables and functions, type :

export -p

Tuesday, August 7, 2012

How do you pass output of a command as a parameter to Perl script?

"xargs" allows you to use the output of one command as the argument to another command. For instance :

<Command Name> | xargs perl myscript.pl

How do you find tables with particular column by name in Sybase?

SELECT Object_name(id)
FROM syscolumns
WHERE name = '<Coulmn Name>'


or

SELECT sysobjects.name
FROM sysobjects, syscolumns
WHERE sysobjects.id = syscolumns.id

AND syscolumns.name = '<Column Name>'

How could you beautify SQL script online?

How could you find out all the table names having a specific column name in SQL?

SELECT COLUMN_NAME, TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%<Column Name>%'

or

SELECT SO.NAME, SC.NAME
FROM SYSOBJECTS SO INNER JOIN SYSCOLUMNS SC
ON SO.ID = SC.ID
WHERE SC.NAME = '<Column Name>'

What is the difference between "IN" and "BETWEEN"?

"BETWEEN" requires a range of values whereas "IN" demands a list of values to operate on.

How could you test your code online?

You can take advantage of the following Online Compilers :

http://ideone.com/
http://codepad.org/
http://compileonline.com/

How could you delete duplicate rows?

DELETE FROM <Table Name>
WHERE rowid not in ( SELECT MIN (rowid)
FROM <Table Name>
GROUP BY column1, column2, column3, ... );

Monday, August 6, 2012

Friday, August 3, 2012

What is the difference between array and hash (associative array) in Perl?

An array is a list of ordered items where as a hash is a set of key-value pairs of unordered items.
To be precise, hash is for mapping and arrays for ordering. Numerically indexed array is more efficient than that of the hash lookup.Hash is slower than array.

If you have things in a line or ordered or in a sequence, use an array. For instance:
- A list of files to read
- A list of people in a queue

If you have a bag of unordered things to look up, use a hash. For example:
- An index of last names, looked up by first name
- An index showing the size of files, looked up by name

What is difference CTLIB and DBLIB?

 An important difference between CTlib and DBlib lies in how the SYBASE environment variable
is handled. DBlib only checks for the SYBASE variable when it requires access to the interfaces file. This allows for definition of the SYBASE variable in the script. CTlib requires the SYBASE variable to be defined BEFORE initialization. If the variable is not defined then CTlib will not initialize properly and the script won't run.

Wednesday, August 1, 2012

What is the difference between "Sybase::BCP" and "Sybase::BLK"?

"Sybase::BCP" is based on "Sybase::CTlib" whereas "Sybase::BLK" on "Sybase::DBlib" though both serves as a simplified front end for Sybase's Bulk Copy library.

What is the maximum number of Index per table in MS SQL Server?

For SQL Server 2005:
 1 Clustered Index + 249 Nonclustered Index = 250 Index
For SQL Server 2008:
 1 Clustered Index + 999 Nonclustered Index = 1000 Index

What is the generic or full syntax of SELECT statement?

SELECT select_list
[ INTO new_table ]
FROM table_source
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]

What is the difference between Clustered and Non-Clustered Index?

Clustered Index
 - describes the order wherein the records are physically stored
 - only one per table
 - faster to read as data is physically stored in index order
 - to enhance insert & update, clustered indexes should be set on a field that is normally incremental i.e. Id or Timestamp

Non Clustered Index
 - defines a logical order that does not match the physical order on disk
 - can be used many times per table
 - quicker for insert and update operations than a clustered index

Can we have a Virtual Constructor?

A constructor assigns value to variables at compile time and the virtual table is created on the fly.
So it is impossible to a have a virtual constructor since the time a constructor is invoked the vtable won't be available in memory;

When does a Copy Constructor get invoked?

The following cases give rise to call a copy constructor:
 1. When an object is returned by value
 2. When an object is passed (to a function) by value as an argument
 3. When an object is thrown
 4 .When an object is caught
 5 .When an object is placed in a brace-enclosed initializer list

How do you debug specific block of code in shell scripting?

You can mention the block of code within "set -x" and "set +x" command. For example :

#!/usr/bin/sh

echo "Welcome"
set -x
echo "Rabindra!"
echo "Nayak"
set +x
echo " to the world!"

What and why are the operators that can't be overloaded?

We can't overload the 'sizeof', ':?', '::', '.' and '.*' operators in C++ since they take name as their argument whereas all other operators take value as argument.