Tuesday, December 27, 2011

Write an example of a multi-threaded program in Perl

#!C:/Perl/bin/perl -w

use strict;
use threads;
use threads::shared;

print "Starting main program\n";
my @threads;

for ( my $count = 1; $count <= 5; $count++)
{
        my $t = threads->new(\&sub1, $count);
        push(@threads, $t);
}

foreach (@threads)
{
        my $num = $_->join;     
}
print "End of main program\n";

sub sub1
{
        my $num = shift;
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
        print "$num thread started at $hour:$min:$sec\n";
        open FILE, ">$num.txt" or die $!;
        print FILE "$num.txt was created at $hour:$min:$sec.\n";
        ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
        print FILE "$num.txt was closed at $hour:$min:$sec.\n";
        close FILE or die $!;
        return $num;
}

Tuesday, December 6, 2011

What does AWK stand for?

awk = "Aho, Weinberger and Kernighan"
This command was named by its authors Al Aho, Peter Weinberger and Brian Kernighan.

Friday, November 18, 2011

How do you convert a chunk of obfuscated or just plain messy and hard to read Perl code into readable format?

We can take advantage of the "Deparse" module. It compiles, then decompiles the program it is given, expanding it out and formatting it nicely.

To run it at the command line, type "perl -MO=Deparse prog.pl". Here is an example
of its usage, showing the input program (red) and the output of Deparse (blue).

$ cat messy.pl
for(74,117,115,116){$::a.=chr};(($_.='qwertyui')&&
(tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X;
/(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");


$ perl -MO=Deparse messy.pl
foreach $_ (74, 117, 115, 116) {
    $a .= chr $_;
}
;
$_ .= 'qwertyui' and tr/eiqrtuwy/nr oteah/ foreach ($b);
foreach $_ ($c) {
    $_ .= $^X;
    /(p.{2}l)/;
    $_ = $1;
}
$b =~ /(..)$/;
print "$a$b $c hack$1.";

Tuesday, November 8, 2011

How can we access environmenttal variables in Perl?

Perl provides access to environment variables via the global %ENV hash. However, if using the Env module, it will create global scalars for all the environment variables.

use Env; print "$USER uses $SHELL";
If required to get only a few selected variables then it can be done like:
 
use Env qw[@PATH $USER]; print "$USER's path is @PATH";

How can we call another program without invokation of shell in Perl?

The system function is Perl's simplest method for accomplishing this. However, one point that should be noted here is: both this program and the Perl program from where we will be running it, will be sharing the same STDIN and STDOUT.

The syntax is like:

$status = system("myprog arg1 arg2");

This particular syntax will invoke the shell, to interpret the command line. In order to avoid the shell's involvement, the arguments for the program being executed should be passed as a list, like:
$status = system("myprog", "arg1", "arg2);

The system function does not return the program's STDOUT, rather its return value is either the program's exit status or the signal number that the process might have died from.

How can we dynamic activate the debugger in Perl?

while (<INPUT>)
   {
   $DB::trace = 1, next if /debug/;
   $DB::trace = 0, next if /nodebug/;
   # more codes
   }
When run under the debugger, this enables tracing when the loop encounters an input line containing "debug" and ceases tracing upon reading one containing "nodebug". We can even force the debugger to breakpoint by setting the variable $DB::single to 1, which also happens to provide a way you can debug code in BEGIN blocks (which otherwise are executed before control is given to the debugger).

Friday, October 21, 2011

Implement semaphore in C.

#include <stdio.h>
#include <pthread.h>

void* thread_a( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp = fopen ("thread_a.txt", "w+");
    fprintf(fp,"%s","thread_a");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

void* thread_b( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp= fopen ("thread_b.txt", "w+");
    fprintf(fp,"%s","thread_b");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

void* thread_c( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp= fopen ("thread_c.txt", "w+");
    fprintf(fp,"%s","thread_c");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

int main()
{
    pthread_mutex_t mtx;
    pthread_t tA;
    pthread_t tB;
    pthread_t tC;
    pthread_mutex_init( &mtx, NULL );
    pthread_create( &tA, NULL, &thread_a, &mtx );
    pthread_join( tA, NULL );  /* wait for the thread_a to finish */
    pthread_create( &tB, NULL, &thread_b, &mtx );
    pthread_join( tB, NULL );  /* wait for the thread_b to finish */
    pthread_create( &tC, NULL, &thread_c, &mtx );
    pthread_join( tC, NULL );  /* wait for the thread_c to finish */
   
    return 0;
}

Monday, October 10, 2011

Friday, October 7, 2011

What is the difference between process and thread?

Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space while processes run in separate memory spaces.

All the threads running within a process share the same address space, file descriptor, stack and other process related attributes. onthe other hand, each process has thier own virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution.

What is the difference between static and shared library?

In Unix, Static library has an extension of ".a" which is equivalent to ".lib" in Windows. on the contrary, dynamic or shared library has got ".so" as extension equivqlent to ".dll" in Windows.

Static libraries increase the size of the code in the binary. It is directly linked into the program at compile time. A program using a static library takes copies of the code from the static library and makes it part of the program. They're always loaded with the currently compiled version of the code. As the code is connected at compile time there are not any additional run-time loading costs.

Dynamic libraries are stored and versioned separately. Dynamic libraries aren't necessarily loaded; they are usually loaded when first called and can be shared among components that use the same library (multiple data loads, one code load). It allows you to replace the shared object with one that is functionally equivalent, but may have added performance advantages without needing to recompile the program that makes use of it.Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

Wednesday, October 5, 2011

How do find out max of 3 numbers using conditional/ternary operator?

#include <stdio.h>

main()
{
    int a, b, c, max;
    printf("Enter three numbers : ") ;
    scanf("%d %d %d", &a, &b, &c);
    max = (a > b) ? (a > c ? a : c) : (b > c ? b : c) ;
    printf("\nThe biggest number is : %d", max) ;
}

Friday, September 30, 2011

Write script that can't be run more than one instance at a time.

#!/bin/sh

if [ -f $0.lock ]; then
        (ps -e | grep $$) >> $0.lock
if [ "$(cat $0.lock | wc -l)" -gt 1 ];then
        echo "\"$0\" is already running with PID=`awk '{print $1}' $0.lock | head -1` !!"
        exit 0
fi
else
        (ps -e | grep $$) > $0.lock
        tn <ServerName>
        rm $0.lock
fi

Write script to create a report of attributes of table of Sybase.

#!/bin/sh

Today=`date '+%d-%m-%y'`
report="report.$Today.txt"

print_header()
{
 awk 'BEGIN{for(c=0;c<50;c++) printf "-"; printf "\n"}'
 echo $0 started on $Today at `date '+%r'`
 awk 'BEGIN{for(c=0;c<50;c++) printf "-"; printf "\n"}'
}
print_footer()
{
 awk 'BEGIN{for(c=0;c<50;c++) printf "-"; printf "\n"}'
 echo $0 ended on $Today at `date '+%r'`
 awk 'BEGIN{for(c=0;c<50;c++) printf "-"; printf "\n"}'
}

print_header >> $report

isql -U<UserName> -P<Password> -S<ServerName> -D<DBName> <<EOF >>$report
set nocount on
select * from <TableName> where 1=2
go
exit
EOF
print_footer >> $report
echo $report has been successfully created!

Thursday, September 29, 2011

Write script to automate FTP uploads from Windows.

@echo off
Title FTP Automation
set cmdscript=%0.txt
echo UserName>%cmdscript%
echo Password>>%cmdscript%
echo hash>>%cmdscript%
echo cd nayakr>>%cmdscript%
echo put My_File.txt>>%cmdscript%
echo ls -lrt>>%cmdscript%
echo disconnect>>%cmdscript%
echo bye>>%cmdscript%
ftp -s:%cmdscript% ServerName
del %cmdscript%

Note : Never use space between command and output file (e.g. "UserName > %cmdscript% " wont work).

Wednesday, September 28, 2011

What is the difference among 'use', 'require' and 'do'?

use - includes file or package at compile time.
require - includes file or package at run time.
do - executes code at run time.

What is the difference among include() vs. require() or include_once() vs. require_once()?

include() and require() allow you to insert a file multiple times within a single execution lifetime. On the other hand, include_once() and require_once() make sure one file is inserted only once in a single execution lifetime, even if the code calls them multiple times.

If PHP interpreter fails to include a file in response to a call of include() or include_once(), a Warning is generated and execution continues without that file whereas failure to include a file called by require() or require_once() generates a Fatal Error and execution stops immediately.

What is the difference between require() and include()?

require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING message.

Write code to connect DB2 and Perl.

#!/usr/bin/perl

use DBI;

#Set Connection String
my $connection_string = "dbi:DB2:DATABASE=$db; HOSTNAME=$hostname; PORT=$port; PROTOCOL=TCPIP; UID=$user; PWD=$pass;";
#Open Connection
my $dbh = DBI->connect($connection_string, $user, $pass) || die "Connection failed for error: $DBI::errstr";
#Set Statement
my $sql = "SELECT * FROM SCHEMA-NAME.TABLE-NAME FETCH FIRST 10 ROWS ONLY";
#Prepare Statement
my $sth = $dbh->prepare($sql) or die "can't prepare: " $dbh->errstr;
#Execute Statement
$sth->execute() or die "can't execute: " $sth->errstr;
#Combine variables with output columns
my ($AppName, $PermValue, $UserName);
$sth->bind_col(1, \$AppName);
$sth->bind_col(2, \$PermValue);
$sth->bind_col(3, \$UserName);
#Iterate through loop to print result set
while ($sth->fetch)
{
        print "$AppName, $PermValue, $UserName\n";
}
$sth->finish();
#Close Connection
$dbh->disconnect();

Monday, September 26, 2011

Write script in Perl to fetch list of files from a specified server using FTP.

#!/usr/bin/perl

use Net::FTP;
use CGI qw(:standard);
$cgi = CGI->new;
$me=`basename $0`;
chomp($me);
$LOG="$me." . "log";
my $REMOTE_SERVER="<ServerName>";
my $login="<UserName>";
my $password="<Password>";
print header(-type=>'text/html'),           # create the HTTP header
      start_html(-title=>'List Files of a Directory of a Remote Server',  # start the HTML
                      -style=>{-code=>'body {background-color: #D6DAFE}
                h1 {font-size: 36pt}
                h2 {color: blue}
                h3 {color : green}
                p {margin-left: 50px}'});
   
print $cgi->start_form(-name=>'PFORM', -method=>'GET', -action=>$action);
$ftp = Net::FTP->new($REMOTE_SERVER, Debug => 1);
$ftp->login($login, $password) or die $ftp->message;
$CURRENT_DIR=$ftp->pwd();
chomp($CURRENT_DIR);
@list=$ftp->ls('-lart');
$ftp->quit() or warn "Couldn't quit.\n";
print $cgi->h3('File List for server :', $REMOTE_SERVER, 'for directory :', $CURRENT_DIR);
print $cgi->hr();
foreach (@list)
{
        print $cgi->h6($_);
}
print $cgi->end_form;
print end_html;

Write a script to automate FTP using "expect" with input parameters.

#!/usr/bin/expect

set host [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set cmd [lindex $argv 3]  # say, "ls -lrt"

spawn ftp $host
expect "login:"
send $user\n
expect "password:"
send $passwd\n
send $cmd\n
send "exit\n"
interact

Write a script to automate login into a server using "telnet+expect".

#!/usr/bin/expect

spawn telnet <ServerName>
expect "login:"
send "<UserName>\n"
expect "password:"
send "<Password>\n"
send "pwd\n"
send "ls -lrt\n"
send "exit\n"
interact

How will you list files in a directory without using ‘ls’ command?

#!/usr/bin/sh

for FILE in *
do
if [ -f $FILE ]
then
echo $FILE
fi
done

How can I use ftp in combination with “.netrc” for anonymous login?

In UNIX/Linux, you can add a “.netrc” file in your HOME directory and completely automate ftp sessions. The “.netrc” may look like :

#more .netrc
machine <ServerName> login <UserName> password <Password>

For Example:
machine rdev200 login ravi password rabindra

The automated script may look like :

#!/usr/bin/sh
ftp -i -v [hostname/ip-address] <<ENDOFSCRIPT
cd [to_dir]
lcd [from_dir]
put <FileName>
bye
ENDOFSCRIPT

What is the difference between Hard link & Soft link?

[a] Hard links cannot links directories ( cannot link /tmp with /home/you/tmp)

[b] Hard links cannot cross file system boundaries ( cannot link /tmp mounted on/tmp to 2nd hard disk mounted on /harddisk2)

[c] Symbolic links refer to a symbolic path indicating the abstract location of another file

[d] Hard links, refer to the specific location of physical data.

What should be shebang/hashbang line for shell scripts to run irrespective of environment?

It is common to need to edit the shebang line after copying a script from one computer to another because the path that was coded into the script may not apply on a new machine, depending on the consistency in past convention of placement of the interpreter. For this and other reasons, the program /usr/bin/env can be used to circumvent this limitation by introducing a level of indirection. “#!” is followed by /usr/bin/env, followed by the desired command without full path as below:

#!/usr/bin/env sh or #!/usr/bin/env perl

Friday, September 23, 2011

Write a batch file that changes text color on each execution.

@echo off
Title Batch Script - By Rabindra Nayak
cls
set R=%random:~-1%
color %R%
echo %0 started at %time% on %date% on %computername% by %username%
pause

How can we load bulk data into Oracle database from a flat file?

SQL*Loader (sqlldr or sqlload) is a bulk loader utility used for moving data from external files into the Oracle database.

The synatx of command is as follows:

sqlldr userid=scott/tiger control=user.ctl log=user.log direct=y

This sample control file (user.ctl) will load an external data file containing comma (by default) delimited data:

LOAD DATA
INFILE '/home/nayakr/User_Permission.csv'
BADFILE ‘/home/nayakr/User_Permission.bad’
DISCARDFILE ‘/home/nayakr/User_Permission.bad’

INSERT INTO TABLE User_Apps
FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'   
( USER, APPS, PERMS )


The 'User_Permission.csv' contains following data:

"NayakR", "Oracle", 2
"NayakR", "DB2", 99

"NayakR", "Sybase", 1

Write code to connect Sybase and C.

#include <sybfront.h>
#include <syberror.h>
#include <sybdb.h>
#include <stdlib.h>
#include <stdio.h>

#define DB_SERVER       "******"
#define DB_USER            "******"
#define DB_PWD              "******"
#define DB_SOURCE      "******"
#define DB_TABLE           "******"

int main()
{
        DBPROCESS    *dbproc;
        LOGINREC     *login;
        DBINT        attachment_id;
        DBINT        row_number = 0;
        RETCODE      return_code;

        if (dbinit() == FAIL)
                exit(ERREXIT);

        login = dblogin ();

        DBSETLUSER (login, DB_USER);
        DBSETLPWD (login, DB_PWD);
        dbproc = dbopen(login, DB_SERVER);

        dbuse(dbproc, DB_SOURCE);
        dbcmd(dbproc, "select top 10 attachment_id from DB_TABLE");
        dbsqlexec(dbproc);

        while ((return_code = dbresults(dbproc)) != NO_MORE_RESULTS)
        {
                if (return_code == SUCCEED)
                {
                        dbbind(dbproc, 1, INTBIND, (DBINT) 0, (BYTE *) &attachment_id);

                        while (dbnextrow(dbproc) != NO_MORE_ROWS)
                        {
                                printf ("%d\n", attachment_id);
                        }
            }
        }

        dbclose (dbproc);
        dbexit();
        return 0;
}

Why do Perl modules end with '1' ?

This line ensures the complier that a module is succesfully loaded (via use or require) or executed and evaluates true. It is a way of making sure that it is parsed all the way to the end of the file. By default, this value is usually 1 though it can be any true value. Therefore it is conventional to end .pm and .pl files with a 1 to provide this value. Moreover, the modules are required to return a value to signal if the require or use directive succeeds or fails. It is a "common fix" to avoid error.

Wednesday, September 21, 2011

What is the equivalent command in Windows for 'echo $0' as in UNIX?

echo '%0'

Write code in Perl to connect to Sybase (SybPerl - CTlib) database and fetch resultset.

#!/usr/bin/perl

use Sybase::CTlib;

my $DB_SERVER_NAME = "******";
my $DB_USER_NAME = "******";
my $DB_USER_PSWD = "******";
my $DB_NAME = "******";
my $DB_TABLE_NAME = "******";

$dbh = new Sybase::CTlib $DB_USER_NAME, $DB_USER_PSWD, $DB_SERVER_NAME;

$dbh->ct_sql("use $DB_NAME");

$dbh->ct_execute("set rowcount 2\select * from $DB_TABLE_NAME");

while($dbh->ct_results($restype) == CS_SUCCEED)
{
    next unless $dbh->ct_fetchable($restype);

    while(@data = $dbh->ct_fetch)
    {
        print "@data\n";
    }
}

How can we execute a '.sql' file from shell script with parameters?

#!/usr/bin/sh

sqlplus -S  <User Id>/<Password> @<path>/script.sql  $param1 $param2 <<ENDOFSQL > $0.$$.`date "+%Y%m%d"`.log
ENDOFSQL

How can you swap two variables without a third variable in C?

main()
{
int a=5,b=7;
a=a+b;
b=a-b;
a=a-b;
printf("a=%d, b=%d", a, b);
}

or

main()
{
int a=5, b=7;
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("a=%d, b=%d", a, b);
}

How do you check availability of a particular Perl module on Unix?

We can use the following perl one liner:

perl -MABC::XYZ -e1

where ABC::XYZ is the name of the module.

Tuesday, September 20, 2011

How do you identify whether a module is part of standard installation in Perl?

The corelist command from the Module::Corelist module will determine if a module is part of standard installation or not. For example,

corelist Carp
Carp was first release with perl 5

What is the difference between warn() and die() in Perl?

The warn function simply raises a warning message to be printed to STDERR. On the otherhand, die function prints error message to the STDERR and terminates the execution of the script as well.

How can you swap values of two variables without a 3rd variable in PHP?

<?php
list($b, $a) = array($a, $b);
?>

Saturday, September 17, 2011

What is 'Deadlock' and 'Livelock'?

Deadlock generally occurs when 2 threads try to acquire same shared resource. In this case each thread end up waiting for other to release lock and deadlock occurs. Deadlock is a common problem in multiprocessing where many processes share a specific type of mutually exclusive resource known as a software lock or soft lock. This could be a case when two threads are trying to write to or update record(s) in a database at a time.

A livelock, on the other-hand, occurs when a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keep interfering. It is an endless loop in program execution. This could be a case when two threads exit allowing each other to write to or update record(s) in a database.

Write code in Perl to connect to Sybase (DBlib) database and fetch resultset.

#!/usr/bin/perl

use Sybase::DBlib;

$DB_SERVER_NAME="******"; #Server Name
$DB_USER_NAME="******";#User Name
$DB_USER_PSWD="******";#Password
$DB_NAME="******";#Database Name
$DB_TABLE_NAME="******";#Table Name
my $DB_CMD="******";#Query to run

my $dbh = new Sybase::DBlib $DB_USER_NAME, $DB_USER_PSWD, $DB_SERVER_NAME;
$dbh->dbuse($DB_NAME);
$dbh->dbcmd($DB_CMD);
$dbh->dbsqlexec;

while($dbh->dbresults != NO_MORE_RESULTS)
{
while(@data = $dbh->dbnextrow)
{
print "@data\n";
}
}
$dbh->dbclose();

Friday, September 16, 2011

Write a program in C to perform multithreading.

/* This code creates log files for each parameter provided at command line. */
/* Compilation : xlc -o thread thread.c -lpthread */
/* Execution : thread */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *ProcessFile(void *arg)
{
char name[32];
char buffer[128];
printf(__FUNCTION__" is processing for argument : %s!\n", (char*)arg);
FILE *FPtr;
sprintf(name, "%s.%s", (char*)arg, "log");
sprintf(buffer, "%s", (char*)arg);
FPtr=fopen(name, "w+");
fprintf(FPtr, "%s", buffer);
fclose(FPtr);
printf("%s has been successfully created!\n", name);
pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
pthread_t threads[argc];
int status;
int i;
if (argc<2)
{
printf("Usage : %s <parameter(s)>\n", argv[0]);
exit(EXIT_FAILURE);
}
else
{
for(i=1; i<argc; i++)
{
printf(__FUNCTION__" : creating thread %d for %s!\n", i, argv[i]);
status=pthread_create(&threads[i], NULL, ProcessFile, (void *)argv[i]);
if (status)
{
printf("ERROR: return code from pthread_create() is %d\n", status);
exit(EXIT_FAILURE);
}
}
pthread_exit(NULL);
}
}

What is Client-Pull and Server-Push paradigm?

Client-Pull refers to a technique that enables a browser/client to request (or "pull") data from the server automatically without the user-intervention. It is a method of initiating delivery of content from a server computer to a client on a network. With this capability, it is possible to have a web page that refreshes/reload itself; or even a web page that loads another page, without the user doing anything. A common implementation of Client Pull is to have the browser automatically move to a different page without the user clicking a hyperlink. For example, sites that have changed their URL might use Client Pull to tell a browser to automatically load the new URL. You could also specify the browser to load the new URL after a time frame has expired.

Server-Push, on the other hand, is method of using server computers to send content independent of requests from client computers. A comman example is bulk mail system that delivers mails to each and every "client". In each case, the transfer of the content is initiated by the server rather than the client. Another example is live notifications in GTalk, a widget that lets GMail users chat online. This application lets the clients know if a new user logs in.

Thursday, September 15, 2011

How do you create and install your own Perl Module Tree?

When there is a need of creating poratable and installable PERL module, then there is standard way of creating a Perl Module Tree. This is done using h2xs utility that comes alongwith PERL. The syntax is as follows:

h2xs -AXn  Module_Name

where :
  • -A omits the Autoloader code (best used by modules that define a large number of infrequently used subroutines)
  • -X omits XS elements (eXternal Subroutine, where eXternal means external to Perl, i.e. C)
  • -n specifies the name of the module
Step 1:
Let's create a module 'Global.pm' triggering the following commands:

h2xs -XAn Global

The output of the command will produce the following files/results :

Writing Global/lib/Global.pm (#contains actual source code)
Writing Global/Makefile.PL
Writing Global/README
Writing Global/t/Global.t (#contains test files)
Writing Global/Changes
Writing Global/MANIFEST (#contains the list of all files in the package)

Step 2:
Now change into the Global/lib subdirectory :

cd Global/lib

Step 3:

Open up the file called Global.pm, using your favorite text editor(Say, Vi) :

vi Global.pm

Step 4:

Find the line 'our EXPORT_TAGS' which should like below:

our %EXPORT_TAGS = ( 'all' => [ qw( ) ] )

Step 5:

Now add name of all sub-routines (Say, printMSG and showDate) to the above line as follows:

our %EXPORT_TAGS = ( 'all' => [ qw(printMSG showDate) ] );

where printMSG and showDate are name of subroutines

Step 6:

Now find the line 'our $VERSION = '0.01';' and add definition of all the sub-routine under the line:

sub printMSG
{
         use Carp;
         my @msg=@_;
         if (!defined($msg[0]))
        {

                 carp "Nothing has been passed to printMSG\n";
        }
         print @msg;
         return wantarray ? @msg : $msg[0];
}


sub showDate
{
        return localtime(time);
}


Step 7:

Now find the line '=head1 SYNOPSIS' and underneath it add your own description:
use Global;

printMSG($msg); # prints user-defined message
showDate(); #shows date

Step 8:

Now save the file (Global.pm) and at the terminal, issue the following command:

perl Makefile.PL

The following messages will be observed if everything is ok :Checking if your kit is complete...
Looks good
Writing Makefile for Global

Step 9:

Now issue the following command:

make

if everthing is fine, following messages will appear:cp lib/Global.pm blib/lib/Global.pm
Manifying blib/man3/Global.3

Step 10:

Run the below command to test:

make test

if everything goes successful, you will see the below output:PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/Global....ok
All tests successful.
Files=1, Tests=1,  0 wallclock secs ( 0.01 cusr +  0.01 csys =  0.02 CPU)
Target "test" is up to date.

step 11 (Installing Perl Module):

Fisrst change to root, or super user and issue the following sequence of commands to install any Perl module:

perl Makefile.PL or
perl Makefile.PL PREFIX=/my/perl/directory (#if you want to install in /my/perl/directory)
make
make install

You may see something like this:
Installing /usr/lib/perl5/site_perl/..../Global.pm
Installing /usr/share/man/man3/Global.3pm
Writing /usr/lib/perl5/site_perl/........./Global/.packlist
Appending installation info to /usr/lib/perl5/......./perllocal.pod

Step 12 (Testing):

To test the module, you may use as follows:

#!/usr/bin/perl

use Global;
use strict;
use warnings;

printMSG("Hi Rabindra");

showDate();

How can you comment out block of statements in Perl?

=begin COMMENT
Statement 1
Statement 2
...
Statement n
=cut

How do you find nth highest salary from an employee table?

SELECT Min (emp_sal)
FROM   employee
WHERE  emp_sal IN (SELECT DISTINCT TOP n emp_sal
                   FROM   employee
                   ORDER  BY emp_sal DESC)

Tuesday, September 13, 2011

How can you get name of table containing a specific column in DB2?

SELECT TABSCHEMA, TABNAME
FROM SYSCAT.COLUMNS
WHERE COLNAME='<Column Name>';

What is inherited from the base class?


In principle, a derived class inherits every member of a base class except:
·         its constructor and its destructor
·         its operator=() members
·         its friends

Predict the output of the following program code.


main()
{
fork(); fork(); fork();
printf("Hello World!");
}

Answer : "Hello World" will be printed 8 times.

Explanation:
2^n times where n is the number of calls to fork()
The fork creates a child that is a duplicate of the parent process. The child begins from the fork().All the statements after the call to fork() will be executed twice.(once by the parent process and other by child). The statement before fork() is executed only by the parent process.

What is the difference between 'malloc()' and 'calloc()'?

malloc():

  • creates the single block (a block of memory in bytes) of given size by user.
  • initializes the reserved memory block to garbage value.
  • takes only one argument.
calloc():
  • creates multiple blocks of given size.
  • initializes the reserved memory block to zero.
  • calloc takes two arguments.
int *p;
p=(int*) malloc(sizeof(int)*5);
p=(int*) calloc(5, sizeof(int)*5);

What are the initialization files/scripts executed for a particular shell to load?

sh - .profile
bash - .bash_profile (or .profile or .bash_login) & .bashrc
ksh - .profile & ENV(or .kshrc)
csh - .login/.cshrc

How do you hide password for authentication in Shell Scripting?

#!/usr/bin/sh

stty_status=`stty -g`
echo "UserName : "
read username
echo "Password : "
stty -echo
read password
stty $stty_status

How do get/put bulk data from/to a Sybase database in UNIX?


#get data
bcp <Database Name>..<Table Name> out /home/nayakr/out.csv -S<Server Name> -U<User Id> -P<Passowrd> -c

#put data
bcp <Database Name>..<Table Name> in /home/nayakr/in.csv -S<Server Name> -U<User Id> -P<Passowrd> -c

How do you comment block of statements in shell scripting?

: ‘
Comments here.
And here.


Or

: <<’END’
Comments here.
And here.
END

How can you find out size of an array in UNIX?

echo ${#array_name[@]}

How can you create a null file in UNIX?

cat /dev/null > <File Name>
or
touch <File Name>

How can you recognize the curent shell (C/Korn/Bourne) you are working on?

First Approach : with prompt symbol

C shell - %
Bourne - $
Ksh - #

Second Approach : UNIX commands

echo $SHELL
or
echo $0

What is the full form of UNIX?

Uniplexed Information Computing System (Previously known as UNICS).

What is the difference between @EXPORT and @EXPORT_OK in Perl?

@EXPORT and @EXPORT_OK are the two main variables used during export operation.

@EXPORT contains list of symbols (subroutines and variables) of the module to be exported into the caller namespace. @Export allows to export the functions and variables of modules to user’s namespace using the standard import method. This way, we don’t need to create the objects for the modules to access it’s members.
@EXPORT_OK does export of symbols on demand basis for selective list of symbols (subroutines and variables) of the module.

How do you use library present in a particular location in Perl?

use lib ("/home/<xyz>/perllib", "/home/<xyz>/perllib/aix", "/home/<xyz>/bin");

Explain the difference between 'use' and 'require' in Perl

use’ loads the module at compile time and imports symbols, semantics from that package to the current one. 'use' only works with modules.

require’ checks for redundant loading, skipping already loaded files and raises an exception on failure to find, compile, or execute file. It also translates each “::” into your system’s directory separator (/). require works with both modules and libraries.

Swap two variables without 3rd variable in Perl

$VAR1="alpha";
$VAR2="omega";
($VAR1, $VAR2) = ($VAR2, $VAR1);

Get date of yesterday in Shell Scripting

Yesterday=`TZ=XYZ+24 date '+%Y%m%d%H%M'`

Perl script to read XML file

#!/usr/bin/perl

# use module
use XML::Simple;
use Data::Dumper;

# create object
$xml = new XML::Simple;

# read XML file
$data = $xml->XMLin("DB.XML");

# access XML data
print "Server : $data->{SERVER}\n";
print "User : $data->{USER}\n";
print "Password : $data->{PASSWORD}\n";
print "Database : $data->{DBNAME}\n";
print "Table : $data->{TABLENAME}\n";

----------------------------------------------------------------------

XML file:

<?xml version ="1.0"?>
<DBCONNECTION>
 <SERVER>ABC</SERVER>
 <DBNAME>DEF</DBNAME>
 <USER>GHI</USER>
 <PASSWORD>JKL</PASSWORD>
 <TABLENAME>MNO</TABLENAME>
</DBCONNECTION>

Perl script to create a XML file

#!/usr/bin/perl

use XML::Simple;

my %commands = (command => [
        {name => 'df',  description => 'Reports file system disk space usage.'},
        {name => 'ls',  description => 'List directory contents.'},
        {name => 'ps',  description => 'Report a snapshot of current processes.'}]
        );
my $xmlObj = XML::Simple->new(RootName => 'commands');
print $xmlObj->XMLout(\%commands, noattr => 1, OutputFile =>'commands.xml', xmldecl =>'<?xml version="1.0">');