Wednesday, December 23, 2015

PERL Questions

Que: What is PERL ?
Ans: Perl is commonly known as an interpreted language, is not strictly true. Since the interpreter actually does convert the program into byte code before executing it, it is sometimes called an interpreter/compiler. Although the compiled form is not stored as a file.
In a single language, Perl combines some of the best features of C, sed, awk, and sh. People familiar with these languages have little difficulty being productive in Perl. Perl's expression syntax is very C-like. Perl uses sophisticated pattern-matching techniques to scan large amounts of data very quickly. Although optimized for scanning text, Perl can also deal with binary data. If you have a problem on which you would ordinarily use sed, awk, or sh, but it exceeds these tools' capabilities or must run a little faster and you don't want to write the program in a compiled language such as C, Perl may be the language for you.

Que : Perl is interpreted language , explain it's use.
Ans : Programming languages generally fall into one of two categories: Compiled or Interpreted. With a compiled language, code you enter is reduced to a set of machine-specific instructions before being saved as an executable file. With interpreted languages, the code is saved in the same format that you entered. Compiled programs generally run faster than interpreted ones because interpreted programs must be reduced to machine instructions at runtime. However, with an interpreted language you can do things that cannot be done in a compiled language. For example, interpreted programs can modify themselves by adding or changing functions at runtime. It is also usually easier to develop applications in an interpreted environment because you don't have to recompile your application each time you want to test a small section. 

Que: Why to use PERL ?
Ans: 
- Portability: A Perl program is platform independent and can run on any operating system
- Large Module Library: Perl has been in development for close to 30 years. This has helped create a huge library of free modules distributed under GNU Public License. These modules can be easily found on CPAN.
- Dynamic Memory Allocation: It is possible to increase or decrease the size of a memory array at any point with Perl, making dynamic memory allocation extremely easy.

Que: What are some of the key features of objects in Perl?
Ans: 
Some of the key-points of objects that need to be remembered in perl are:
- Every object are anonymous hashes: This means that most of the new() methods return a reference to a hash.
- Data type changed by bless() method: The data type of anonymous hashes is changed to the name of the class by the bless() method.
- The anonymous hash are blessed: This implies references to the hash are not blessed.
- Objects belong to one class at a time: You can use the bless() function to change the ownership at any time but it is not usually preferred.
- The -> operator is used to call a method associated with a class: There are two different ways to invoke or call class methods:
$item = new Invent_item;
$item = Invent_item->new();

Que: built-in debugger in PERL - how to use it / why to use it ?
Ans: 

Que : In Perl, there are some arguments that are used frequently. What are that arguments and what do they mean?
Ans:
-w (argument shows warning)
-d (use for debug)
-c (which compile only not run)
-e (which executes)
We can also use combination of these like:
-wd

Que: Difference between Package and module ?
Ans:
namespace : is a container of identifiers (variables, functions). A namespace would be Some::Thing.

symbol-table : is the place where the identifier of a namespace are stored. Basically we can think of a symbol-table as being equivalent to namespace.

package : is a keyword of Perl that switches to a new namespace. Sometimes people refer to a particular release or a distribution as being a package, but that only happens because when we zip up several files of a release we often think about the English word package.

module : is the name of a package (namespace) that is kept in a file derived from its name. (a package/namespace called Some::Thing kept in a file called Some/Thing.pm is called a module. Unfortunately when we say "module" we often refer to a whole distribution.

Que : Which functions in Perl allows you to include a module file or a module and what is the difference between them?
Ans:
“use”
1. The method is used only for the modules (only to include .pm type file)
2. The included objects are verified at the time of compilation.
3. We don’t need to specify the file extension.
4. loads the module at compile time.

“require”
1. The method is used for both libraries and modules.
2. The included objects are verified at the run time.
3. We need to specify the file Extension.
4. Loads at run-time.

suppose we have a module file as “Module.pm”

use Module;
or
require “Module.pm”;
(will do the same)

Que : Can you include the .pl file in another .pl file ?
Ans :
Perl require will do the job. You will need to ensure that any 'require'd files return truth by adding
1;
at the end of the file.

Here's a tiny sample:

$ cat m1.pl
use strict;
sub x { warn "aard"; }
1;

$ cat m2.pl
use strict;
require "m1.pl";
x();

$ perl m2.pl
aard at m1.pl line 2.
But migrate to modules as soon as you can.

Que: Difference between %INC, @INC & %ENV ?
Ans:
%INC : Displays all the modules included in currently executing PERL script.
@INC : Displays all the libraries included in currently executing PERL script.
%ENV : Displays all the environment variables.

Que: How can you define “my” variables scope in Perl and how it is different from “local” variable scope?
Ans:
Quick summary: 'my' creates a new variable, 'local' temporarily amends the value of a variable. There is a subtle difference.
In the example below, $::a refers to $a in the 'global' namespace.

====================================
$a = 3.14159;
{
 local $a = 3;
 print "In block, \$a = $a\n";
 print "In block, \$::a = $::a\n";
}
print "Outside block, \$a = $a\n";
print "Outside block, \$::a = $::a\n";

# This outputs
In block, $a = 3
In block, $::a = 3
Outside block, $a = 3.14159
Outside block, $::a = 3.14159
====================================

$test = 2.3456;
{
my $test = 3;
print "In block, $test = $test ";
print "In block, $::test = $::test ";
}
print "Outside the block, $test = $test ";
print "Outside the block, $::test = $::test ";

Output:
In block, $test = 3
In block, $::test = 2.3456
Outside the block, $test = 2.3456
Outside the block, $::test = 2.3456
====================================
The scope of “my” variable visibility is in the block only but if we declare one variable local then we can access that from the outside of the block also. ‘my’ creates a new variable, ‘local’ temporarily amends the value of a variable. local doesn't create variables.
use local when:
you want to amend a special Perl variable, eg $/ when reading in a file. my $/; throws a compile-time error.
In below code have a look at "our".

#! /usr/bin/perl -w

use strict;
our $aa = 11;
{
local $aa = 22;
print $aa."\n";
print $::aa."\n";
}
print $aa."\n";

But most of all my is lexically scoped while our is lexical scope but their life persistent even outside the declaring block(their life is like global variable life), therefore to really understand the difference between my and our you have to understand the difference between lexically and global scoped in Perl. So briefly the difference between the two type are :

Global variables : Any code, anywhere, can change their values.
Lexical variables : The life of the variable end with the the end of the code block in which they are included, after that their values are garbage collected. These kind of variables can be accessed only within the block in which they are declared.

Que : What is our in perl ?
Ans : our is used to declare variables globally. You can access them from other packages also without specifying class name.

Que : Clear the concepts of Polymorphism, Overriding, Overloading, Data hiding,... 
Ans :
Polymorphism : Polymorphism is mainly used to add or extend the functionality of an existing class without reprogramming the whole class.

Creating Method Override (Polymorphism)
Ans : Polymorphism means that methods defined in the base class will override methods defined in the parent classes and is mainly used to add or extend the functionality of an existing class without reprogramming the whole class.

The following simple Perl code demonstrate the concepts of Polymorphism (Method overriding):

Source: Polymorphism.pl
#!/usr/bin/perl

package parent;
  sub foo {
print "Inside the parent. \n";
  }

Method overriding :

Base Class : Bean.pm
Child Class : Coffee.pm
PERL FIle : Normal PERL script to create object of Coffee.pm

$cup->Coffee::printType();
$cup->printType();
$cup->Bean::printType();
$cup->SUPER::printType();

#Inheritance: is accomplished by placing the names of parent classes into a special array called @ISA.

package child;
  @ISA = (A);
  sub foo {
print "Inside the child. \n";
  }

package main;
  child->foo();

Output: perl Polymorphism.pl
Inside the child.

Can inheritance be used in perl? Explain with the help of an example.

Yes perl allows inheritance in order to promote code reusability. Inheritance as the name suggests means the properties and methods of a parent class will be available to their child classes. Inheritance can be done in perl by making the use of the special array @ISA. The names of the parent classes are placed into this array. The elements of the array @ISA are always searched from left to right to check for any missing methods.
For ex.
package A;
sub foo {
print("Inside A::foo\n");
}
package B;
@ISA = (A);

package main;
B->foo();
B->bar();

Que : Why does Perl not have overloaded functions?
Ans : Because you can inspect the argument count, return context, and object types all by yourself. In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they're references and simple pattern matching like /^d+$/ otherwise. In languages like C++ where you can't do this, you simply must resort to overloading of functions.

Que : Given a file, count the word occurrence (case insensitive)
Ans : open(FILE,"filename");
@array=<FILE>;
$wor="word to be found";
$count=0;
foreach $line (@array)
{
@arr=split (/s+/,$line);
foreach $word (@arr)
{
if ($word =~ /s*$wors*/i)
$count=$count+1;
}
}
print "The word occurs $count times";

Que : perl regular expressions are greedy" what does this mean?
Ans : Perl regular expressions normally match the longest string possible. that is what is called as "greedy match" 
For instance:
my($text) = "mississippi";
$text =~ m/(i.*s)/;
print $1 . " ";
Run the preceding code, and here's what you get: ississ 
It matches the first i, the last s, and everything in between them. But what if you want to match the first i to the s most closely following it? Use this code:
my($text) = "mississippi";
$text =~ m/(i.*?s)/;
print  $1 . " ";

Now look what the code produces: is
Que: What interface used in PERL to connect to database? How do you connect to database in Perl?
Ans: We can connect to database using DBI module in Perl.

       use DBI;
       my $dsn = "dbi:ODBC:<dsn_name>";   $dsn = "dbi:mysql:database_name:localhost:port"
       my $dbh = DBI->connect($dsn, $user, $auth);

For Oracle:

       my $dbh = DBI->connect('dbi:Oracle:orcl', 'username', 'password',)

For Sybase:

my $dbh = DBI->connect('dbi:Sybase:server=$SERVER', 'username', 'password')

Que:  What does the command "use strict" do and why should you use it?
Answer: "Use strict" is one of the pragma used for checking the variable scope and syntax.  If you use this pragma means, you need to specify the scope (my,local, our) for the variable and use the exact usage of operators.For eg. Checking equality   $number = 1 and $char eq 'a'.

Que:  What do the symbols $ @ and % mean when prefixing a variable?
Answer:
$ indicate scalar data type
@ indicates an array and 
% indicates an hash or an associative array.

Que: Types of inheritance applicable in PERL ? Multiple / Multilevel ?
Ans: I think both, but not sure.

Que: What is the usage of -i and 0s options?
Ans: The -i option is used to modify the files in-place. This implies that Perl will rename the input file automatically and the output file is opened using the original name. If the -i option is used alone then no backup of the file would be created. Instead -i.bak causes the option to create a backup of the file.

Que: Why Perl aliases are considered to be faster than references?
Ans: In Perl, aliases are considered to be faster than references because they do not require any dereferencing.

Que: Where do you go for perl help? 
Answer:
perldoc -f function name
perldoc -q keywords

Que: What are the perl one-liners?
Ans: There are two ways a Perl script can be run:

1. from a command line, called one-liner, that means you type and execute immediately on the command line. You'll need the -e option to start like "C:> perl -e "print "Hello";". One-liner doesn't mean one Perl statement. One-liner may contain many statements in one line.
2. from a script file, called Perl program.

Que: List the prefix dereferencer in Perl.
Ans: There are six prefix dereferencer available in perl they are:
(i) $-Scalar variables
(ii) %-Hash variables
(iii) @-arrays
(iv) &-subroutines
(v) ( - code
(vi) * - typeglob

Que: Mention the difference between die and exit in Perl?
Ans: Die will print a message to the std err before ending the program while Exit will simply end up the program.
1) die is used to throw an exception (catchable using eval).
exit is used to exit the process.
2) die will set the error code based on $! or $? if the exception is uncaught.
exit will set the error code based on its argument.
3) die outputs a message
exit does not.

Que : Difference between Perl and Mod_perl?
Ans : Perl is a language and MOD_PERL is a module of Apache used to enhance the performance of the application.

Que : Why we use "use lib $path"?
Ans : If we are trying to add a module or library files in our program using require or use statement then it will search that module or library files in the Perl's default search path. The statement use lib is used to add the directories to default search path. So if the module or library file is not located in the
Perl's default search path then it will find the library files in the path we have given with the use lib $path.

Que: How would you replace a char in string and how do you store the number of replacements? 
Ans: my $count = ($string =~ s/$char/$replacement/g);

Que: What is the syntax used in Perl grep function?
Ans: my @arr = grep { /^A/ } @test_arr;

Que: What is the syntax used in Perl map function?
Ans: @square = map {$_ * $_} @array;
%hash = map{$_=>1} @array;

Que: What chomp and chop function does ?
Ans: Chomp function eliminates the last character from an expr or each element of the list if it matches the value of $/. It is considered better than chop as it only removes the character if there is a match.
$/ = input record separator

The chop function deletes the last ending variable character regardless of whatever it is, the Perl chomp function checks whether the last character matches the input line separator and only then it deletes it. Perl chomp function returns the number of characters removed.

$/ = "";
$v = "\n\nsome text here\n\n\n\n";
$nr = chomp $v;

After executing this code, the first two newlines will remain unchanged, but the last four will be removed. The variable $nr will be set to 4 – the number of newline characters removed. Be careful, however, when you alter the content of the special variable $/, and restore it to its default value (\n), when you consider necessary.

CPAN : Comprehensive Perl Archive Network

Que: What is use of ‘->’ symbol?
Ans : In Perl, ‘->’ symbol is an infix dereference operator. if the right hand side is an array subscript, hash key or a subroutine, then the left hand side must be a reference.

Que : Find uniq array elements in an array ?
Ans :
my %seen;
my @unique = grep { ! $seen{$_}++ } @faculty;

Que : Create hash from an array in one line ?
Ans :
my %hash = map { $_ => 1 } @array;

grep returns those elements of the original list that match the expression, while map returns the result of the expression applied to each element of the original list.

$ perl -le 'print join " ", grep $_ & 1, (1, 2, 3, 4, 5)'
1 3 5
$ perl -le 'print join " ", map $_ & 1, (1, 2, 3, 4, 5)'
1 0 1 0 1
The first example prints all the odd elements of the list, while the second example prints a 0 or 1 depending on whether the corresponding element is odd or not.


Que : What are the three ways to empty an array? 

Ans : The three different ways to empty an array are as follows
1) You can empty an array by setting its length to a negative number.
2) Another way of empting an array is to assign the null list ().
3) Try to clear an array by setting it to undef, but be aware when you set to undef.

In 3 ways..
1. @arr= -1;
2. @arr= ();
3. @arr = undef;

Que : What exactly is grooving and shortening of the array? 
Ans : You can change the number of elements in an array simply by changing the value of the last index of/in the array $#array. In fact, if you simply  refer to a non existent element in an array perl extends the array as needed, creating new elements. It also includes new elements in its array.

Que : How do you give functions private variables that retain their values between calls? 
Ans : Create a scope surrounding that sub that contains lexicals.
Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus:
{ my $i = 0; sub next_i { $i++ } sub last_i { --$i } }
creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.

Que : What does this symbol mean '->'
Ans : In Perl it is an infix dereference operator. The if the rhs is an array subscript, or a hash key, or a subroutine, then the lhs must be a reference, can also be used as method invocation: invocant->method  

Que : When do you use Perl for a project?
Ans : When there's a lot of text processing- Web-based applications- Fast/expidient development - Shell scripts grow into libraries- Heavy Data manipulation (auditing, accounting, checking etc... backend processing)- Data extraction - transform - loading (database etc.)- System admin etc. Only in the case of high performance graphics scenarios, like games, etc.For all the other cases Perl can be used somehow.

Que : How many ways can we express string in Perl?
Ans : Many. For example 'this is a string' can be expressed in:
"this is a string"
qq/this is a string likee double-quoted string/
qq^this is a string like double-quoted string^
q/this is a string/
q&this is a string&
q(this is a string)

Que : Find All Files of a Particular Size
Ans :
  find /home/ -type f -size 6579c -exec ls {} \;
find /home/ -type f -size +512k -exec ls -lh {} \;

b – for 512-byte blocks (this is the default if no suffix is used)
c – for bytes
w – for two-byte words
k – for Kilobytes (units of 1024 bytes)
M – for Megabytes (units of 1048576 bytes)
G – for Gigabytes (units of 1073741824 bytes)

Que : How to Sort Folders by Size With One Command Line in Linux
Ans :
  du --max-depth=1 /home/ | sort -n -r
du -H --max-depth=1 /home/user


Que: How do I read command-line arguments with Perl? 
Answer: With Perl, command-line arguments are stored in the array named @ARGV.$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1. Here's a simple program:

#!/usr/bin/perl
$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments. ";
foreach $argnum (0 .. $#ARGV) {
print "$ARGV[$argnum] ";
}

Que: How to concatenate strings with Perl?
Answer:
Method #1 - using Perl's dot operator:
$name = 'checkbook';
$filename = "/tmp/" . $name . ".tmp";

Method #2 - using Perl's join function
$name = "checkbook";
$filename = join "", "/tmp/", $name, ".tmp";

Method #3 - usual way of concatenating strings
$filename = "/tmp/${name}.tmp";

Que : What is the difference between find and locate ?
Ans :

Que : How to mount Remote Folders via SSH ?
Ans :

Que : What are the different types of modules used in perl
Ans :
- WWW::Mechanize
- Data::Dumper
- File::Path
- File::remove
- File::Spec - to run linux cmds on windows
- Encode
- Date::Calc
- Storable - store and retrieve

Que List the programming guidelines that must be followed when programming with Perl modules:
Ans :
- The Module and the package name must be the same.
- When referring to a package name, it must ALWAYS begin with a capital letter.
- The only allowable package name needs to have the extension “.pm”.
- The package must be derived from the exporter class when no object-oriented technique is used.
- When no object-oriented techniques are used, the module must export all functions utilising the @EXPORT and @EXPOR_OK methods.

Que: What are some of the distinct advantages of Perl over C programming language?
Ans : 
- Portability: A Perl program is platform independent and can run on any operating system, while C requires use of a cross-compiler to port code between operating system.
- Large Module Library: Perl has been in development for close to 30 years. This has helped create a huge library of free modules distributed under GNU Public License. These modules can be easily found on CPAN. With C, however, one has to write programs completely from scratch.
- Dynamic Memory Allocation: It is possible to increase or decrease the size of a memory array at any point with Perl, making dynamic memory allocation extremely easy.

Que : What does 'qw(..)' mean? What's the use of it? when do we use it?
Ans : qw is a construct which quotes words delimited by spaces. use it 
when you have a long list of words that are not quoted or you just don't want to type those quotes as you type out a list of space delimited words

Que : What's the significance of @ISA, @EXPORT @EXPORT_OK %EXPORT_TAGS list & hashes in a perl package? With example?
Ans : @ISA -> each package has its own @ISA array. this array keep track of classes it is inheriting.
For Ex:
package child;
@ISA=( parentclass);
@EXPORT this array stores the subroutines to be exported from a module.
@EXPORT_OK this array stores the subroutines to be exported only on request.

Que: What is the difference between exec, system & backticks?
Answer: 
exec : executes a command and never returns. It's like a return statement in a function. If the command is not found exec returns false. It never returns true, because if the command is found it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in  perlfunc, because it is a function.

system : executes a command and your Perl script is continued after the command has finished. The return value is the exit status of the command. You can find documentation about it in  perlfunc.

backticks : like system executes a command and your perl script is continued after the command has finished. In contrary to system the return value is STDOUT of the command.  qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and execit is an operator.

Write a simple (common) regular expression to match an IP address, e-mail address, city-state-zipcode combination. 


==> Converting Floats into Integers:

The quickest and simplest way to convert floating-point numbers into integers is to use the int
function. This strips off the fractional part of the floating-point number and returns the integer part:
      $int = int($float);

$number = 4.05/0.05;
print "$number \n";  # returns 81, correct
print int($number);  # returns 80, incorrect!

printf '%e', $floatnum; # force conversion to fixed decimal format
printf '%f', $floatnum; # force conversion to mantissa/exponent format
printf '%g', $floatnum; # use fixed if accurately possible, otherwise

===>
Modifier Meaning

/i Case-insensitive matching.
/m ^ and $ match next to embedded \n.
/s Dot (.) matches newline.
/x Ignore whitespace, and allow comments (#) in pattern.
/o Compile pattern only once.



curl "url" -I ====> prints only header information without downloading that page



 ” Scalar variables are prepended with the symbol $. For array and hash variables, the symbols are
   @ and % respectively.
 ” Scalar variables can be assigned a value by using the assignment operator =. A variable holds the
   value undef by default.
 ” Variable names are case-sensitive. They should start with an alphabet or an underscore character
   ( ). Subsequent characters may be decimal digits as well. Variables whose names not conforming
   to this nomenclature are predefined by Perl and serve special purposes.
 ” Variable substitution means variables embedded in a double-quoted string will be substituted by
   their respective values at the instant the string is evaluated.
 ” The substr() function extracts a sequence of characters from a given string.
 ” The length() function returns the number of characters in a given string.
 ” A list is an ordered set of scalar values. An array is a list associated with a name.
 ” An array may be created by assigning a list to an array variable.
 ” Nested lists are merged to form a single list when the list is evaluated, with null lists removed.
 ” The reverse() function returns a list whose items are identical to the input list except the items
   are arranged in reverse order.
 ” The push() function may be used to append a list of items to the end of an array.
 ” The unshift() function prepends a list of items to the beginning of an array.
 ” The subscript operator [] can be used to access a subset of elements in a list or an array.
 ” The pop() and shift() functions may be used to remove an item from an array. pop() removes
   the last item while shift() removes the first item.
 ” splice() is a general purpose function to add or remove array elements.
 ” join() concatenates a list of scalars into a string, inserting a string in between.
 ” map() executes a given code block for each list element, and the results evaluated are combined to form an array.
 ” Searching an array is not efficient. A hash should be used instead.
 ” A hash may be initialized by assigning it a list, whose elements are treated as a list of key-value
   pairs.
 ” To refer to a hash element, use curly braces with the key in between.
 ” The delete() function may be used to remove a key-value pair from a hash.
 ” You may use the exists() function to test if a given key exists in the hash. The defined()
   returns if a value is not undef.
 ” Behaviours of Perl operators and functions are influenced by context. The scalar() function
   forces a scalar context in an otherwise list context.
 ” The result of evaluating an array in scalar context is the number of items in the array. Evaluating
   a list in scalar or void context causes all list items to be evaluated, and the value of the last item is
   returned.



Que : What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), $ap ]; }' ?
Ans : Their destructors are called when that interpreter thread shuts down. When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code.

Que : What are the different types of eval statements? 
Ans : There are two different types of eval statements they are eval EXPR and eval BLOCK. Eval EXPR executes an expression and eval BLOCK executes BLOCK. Eval Block executes an entire block, BLOCK. First one is used when you want your code passed in the expression and the second one is used to parse the code in the block.
EVAL EXPR
# Compile time error
eval { $answer = $a / $b; }; warn $@ if $@;
# same thing, but less efficient : run time error
eval '$answer = $a / $b'; warn $@ if $@;

EVAL BLOCK
{
# -------- any code -------- #
}



Que : Explain about Typeglobs? 
Ans : Type globs are another integral type in perl. A typeglob`s prefix derefrencer is *, which is also the wild card character because you can use typeglobs to create an alias for all types associated with a particular name. All kinds of manipulations are possible with typeglobs.


Que: What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?
Answer: the element is keyword "sub" means write the subroutines,which allow maximum readability and allow maximum-reuse if want any other;
write the classes and package..

Que: Why do you program in Perl?
Answer: Perl is a general purpose, high level, interpreter, dynamic and open souce programming language. It's a powerful text processing software and also used in system administration, web developement, network programming language etc. We can use it in both linux/unix and Windows environment also. Hope this should be enough to the reason for programming in PERL.

Que: What arguments do you frequently use for Perl Interpreter.
Answer:
-T for taint mode for security/input-checking
-W for show all warnings mode (or -w to show less warnings)

Que: How do I set environment variables in Perl programs?
Answer: As you may remember, "%ENV" is a special hash in Perl that contains the value of all your environment variables.Because %ENV is a hash, you can set environment variables just as you'd set the value of any Perl hash variable. Here's how you can set your PATH variable to make sure the following four directories are in your path :: $ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/home/yourname/bin';

Que: What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), $ap ]; }' ?
Answer: Their destructors are called when that interpreter thread shuts down. When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code.

Que: What is the easiest way to download the contents of a URL with Perl?
Answer: Once you have the libwww-perl library, LWP.pm installed, the code is this:

#!/usr/bin/perl
use LWP::Simple;
$url = get 'http://www.websitename.com/';

Que: Perl uses single or double quotes to surround a zero or more characters. Are the single(' ') or double quotes (" ") identical? 
Answer: They are not identical. There are several differences between using single quotes and double quotes for strings.
1. The double-quoted string will perform variable interpolation on its contents. That is, any variable references inside the quotes will be replaced by the actual values.
2. The single-quoted string will print just like it is. It doesn't care the dollar signs.
3. The double-quoted string can contain the escape characters like newline, tab, carraige return, etc.
4. The single-quoted string can contain the escape sequences, like single quote, backward slash, etc.

Que: What is __FILE__ , __PACKAGE__ , __LINE__ ? 

#!/usr/bin/perl

print "File name ". __FILE__ . "\n";
print "Line Number " . __LINE__ ."\n";
print "Package " . __PACKAGE__ ."\n";





Thursday, October 8, 2015

Perl BLOCKS

The BEGIN Block


The BEGIN block is evaluated as soon as it is defined. Therefore, it can include other functions using do() or require statements. Since the blocks are evaluated immediately after definition, multiple BEGIN blocks will execute in the order that they appear in the script.
For Example (export.pl):

  • Define a BEGIN block for the main package.
  • Display a string indicating the begin block is executing.
  • Start the Foo package.
  • Define a BEGIN block for the Foo package.
The Perl code is (export.pl):

BEGIN {

    print("main\n");

}

package Foo;

    BEGIN {

        print("Foo\n");

   }

This program displays:

main
Foo

The END Block



The END blocks are the last thing to be evaluated. They are even evaluated after exit() or die() functions are called. Therefore, they can be used to close files or write messages to log files. Multiple END blocks are evaluated in reverse order.

END {

    print("main\n");

}

package Foo;

    END {

        print("Foo\n");

    }
This program displays:

Foo
Main

Note Signals that are sent to your script can bypass the END blocks. So, if your script is in danger of stopping due to a signal, be sure to define a signal-handler function. See Chapter 13, "Handling Errors and Signals," for more information.

$SIG{INT}  = \&interrupt;
$SIG{TERM} = \&interrupt;




Thursday, April 9, 2015

SQL driver installation on Linux

Check if your system has already installed unixODBC and its version using command with root login.

                yum list installed unixODBC*

We are installing unixODBC-2.3.0

                yum remove unixODBC

Go to: http://www.unixodbc.org/ - Click on Download – This will download ‘unixODBC-2.3.0.tar.gz’ file, copy to Linux machine. 

1.       For further steps go to the ‘Manual Installation’ section of the link – ‘https://technet.microsoft.com/en-us/library/hh568449(v=sql.110).aspx’

OR

1.       On your Linux computer, execute the command: tar xvzf unixODBC-2.3.0.tar.gz

2.       Change to the unixODBC-2.3.0 directory.

3.       At a command prompt, execute the command: CPPFLAGS="-DSIZEOF_LONG_INT=8"

4.       At a command prompt, execute the command: export CPPFLAGS

5.       At a command prompt, execute the command: "./configure --prefix=/usr --libdir=/usr/lib64 --sysconfdir=/etc --enable-gui=no --enable-drivers=no --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE"

6.       At a command prompt (logged in as root), execute the command: make

7.       At a command prompt (logged in as root), execute the command: make install


Then we have to install msodbcsql-11.0.2270.0.tar.gz

Go to link: http://www.microsoft.com/en-in/download/details.aspx?id=36437, download the module, copy to Linux machine. For further installation steps, go to link - https://technet.microsoft.com/en-us/library/hh568454(v=sql.110).aspx.         
      
OR

These instructions refer to msodbcsql-11.0.2270.0.tar.gz, which is installation file for Red Hat Linux. If you are installing the CTP for SUSE Linux, the file name is msodbcsql-11.0.2260.0.tar.gz.

To install the driver:


  1. Make sure that you have root permission.

  1. Change to the directory where the ODBC driver on Linux placed the file called msodbcsql-11.0.2270.0.tar.gz. Make sure that you have the *.tar.gz file that matches your version of Linux. To extract the files, execute the following command, tar xvzf msodbcsql-11.0.2270.0.tar.gz.


  1. Change to the msodbcsql-11.0.2270.0 directory and there you should see a file called install.sh.

  1. To see a list of the available installation options, execute the following command: ./install.sh

  1. Make a backup of odbcinst.ini. The driver installation updates odbcinst.ini. odbcinst.ini contains the list of drivers that are registered with the unixODBC Driver Manager. To discover the location of odbcinst.ini on your computer, execute the following command: odbc_config --odbcinstini

  1. Before you install the driver, execute the following command: ./install.sh verify. The output of ./install.sh verify reports if your computer has the required software to support the ODBC driver on Linux.

  1. When you are ready to install the ODBC driver on Linux, execute the command: ./install.sh install . If you need to specify an install command (bin-dir orlib-dir), specify the command after the install option.

  1. After reviewing the license agreement, type YES to continue with the installation.
Installation puts the driver in /opt/microsoft/msodbcsql/11.0.2270.0. The driver and its support files must be in /opt/microsoft/msodbcsql/11.0.2270.0.
To verify that the ODBC driver on Linux was registered successfully, execute the following command: odbcinst -q -d -n "ODBC Driver 11 for SQL Server"


Go to CPAN shell, install PERL module - install DBD::ODBC

After this add below line in /etc/odbc.ini file.

[Review]
Driver=/opt/microsoft/msodbcsql/lib64/libmsodbcsql-11.0.so.2270.0
Server=122.xx.xx.xxx
Database=Review_Project_1
Trace=Yes

Below command is used to test connection:

                isql -v "Review" {username} {password}

If you get the result like below, that means you are connected successfully.

+------------------------------------+
| Connected!                               |
| sql-statement                            |
| help [tablename]                      |
| quit                                           |
+------------------------------------+


You are ready to connect through PERL code. Cheers :)


Tuesday, April 7, 2015

Add & Remove entries from crontab

Add Entry : 

system ( "crontab -l > oldcrontab_$pid ; cp oldcrontab_$pid newcrontab_$pid ; echo '$min $hour $day $mon * perl /home/username/development/script.pl > /home/usrename/logs/data.log 2>&1' >> newcrontab_$pid ; crontab newcrontab_$pid; rm -f newcrontab_$pid oldcrontab_$pid");


Remove Entry : 

open my $fh, "| crontab -" || die "can't open crontab: $!";
my $cron = qx(crontab -l);
$cron =~ s!\#\*\/02 \* \* \* \* \/home\/username\/perl execute.sh > \/home\/username\/file.log 2>\&1!!;
print $fh $cron;
close $fh;