Friday, March 8, 2013

How could you check the existence of a function (say new) within a package (say CGI) in Perl?

use CGI;

$cgi=CGI->new;

if (exists &CGI::new)
{
    print "Exists\n";
}

Or

if ( defined( &CGI::new ) )
{
print "Defined\n";
}

Or

if ( CGI->can('new') )
{
print "Exists\n";
}

Or

if ( $cgi->can('new') )
{
print "Defined\n";
}

How could you list out all the variables defined in a package in Perl?

use CGI;

no strict 'refs';

foreach ( keys %CGI:: )
{
print "$_\n";
}

How could you list all the methods defined in the package (say CGI) in Perl?

use CGI;

no strict 'refs';
print join ', ', grep { defined &{ "CGI::$_" } } keys %{ CGI:: };

When is “use lib” implemented in Perl?

‘use lib’ is used in two cases:
  • When you have a fixed, but not standard company-wide environment in which you put modules in a common standard location.
  • When you are developing an application and you'd like to make sure the script always picks up the modules relative to their own location.

Thursday, March 7, 2013

How could you disable strict for a block of code in Perl?

It can be disabled with "no strict".

#!/usr/bin/perl
use strict;
 
my $me=$0;
print "$me\n";
 
open (FH, "< $0") or die "$!";  
while (<FH>)
{
no strict;
  $count=0;  
print "$_" . ++$count;
}

How could you extract range of characters in a fixed string in UNIX?

echo "Hello World!" | cut -c 3-7

Wednesday, March 6, 2013

Tuesday, March 5, 2013

How could you execute command stored in a string or variable in Shell Scripting?

#!/bin/bash

CMD="ls -lrt"
eval $CMD

How could you run commands/scripts when you log out session in UNIX?

Run commands/scripts when you log out by appending required lines to the ".logout" file in your HOME directory.

sh shell : ~/.sh_logout
bash shell : ~/.bash_logout
ksh shell : ~/.ksh_logout
tcsh / csh : ~/.logout

Next add the below line to your ".profile" file :
trap '. $HOME/.sh_logout; exit' 0

Saturday, March 2, 2013

How could you generate a sequence of numbers in Shell Scripting?

#!/bin/bash

for (( count=1; count <= 3 ; count++ ))
do
 echo "Value of count = $count."
done

# Or

#!/bin/bash

for count in $(seq 4 7)
do
 echo "Value of count = $count."
done

# Or

#!/bin/bash

for count in {7..10}; do
 echo "Value of count = $count."
done