Shell Scripting Interview Questions

Shell Scripting Interview Questions


1.    What Are Pids?

They are process IDs given to processes. A PID can vary from 0 to 65535.

2.    How Do You Remove A File?

"rm" removes each specified file argument (provided that it is a valid path name). If you specify either. or.. as the final component of the path name for a file, rm displays an error message, and moves onto the next file. If you specify a file you do not have write permission for, rm asks you for confirmation.

3.    How Do You Remove Recursively?

rm -rf.

4.    How Do You Find Out Your Own Username?

Whoami.

5.    How Do You Count Words, Lines And Characters In A File?

Wc  

6.    How Do You Search For A String Inside A Given File?

grep string filename.

7.    How Do You Search For A String Inside A Directory?

      grep string *.

8.    How Do You Search For A String In A Directory With The Subdirectories Recursed?

grep -r string *.

9.    How Do You List Currently Running Process?

PS.

10. How Do You Find Out What's Your Shell?

     echo $SHELL.

11. How Do You Fire A Process In The Background?

process-name &.

12. What's The Conditional Statement In Shell Scripting?

if {condition} then …... fi.

 

13. How Do You Do Number Comparison In Shell Scripts?

-eq, -ne, -lt, -le, -gt, -ge.

 

14. How Do You Test For File Properties In Shell Scripts?

-s filename tells you if the file is not empty,

     -f filename tells you whether the argument is a file, and not a directory,

     -d filename tests if the argument is a directory, and not a file,

     -w filename tests for writeability,

     -r filename tests for readability.

     -x filename tests for executability

15. How Do You Do Boolean Logic Operators In Shell Scripting?

   tests for logical not, -a tests for logical and, and -o tests for logical or.

16.  How Do You Find Out The Number Of Arguments Passed To The Shell Script?

S$

17. What's The Way To Do Multilevel If-else's In Shell Scripting?

     if {condition} then {staternent} elif {condition} {statement} fi.

18. How Do You Write A For Loop In Shell?

for {variable name} in {list} do {statement} done.

19. How Do You Find Out The Current Directory You're In?

pwd.

20. What's The Command To Find Out Users On The System?

     who.

21. What's The Command To Find Out Today's Date?

       date.

22. How Do You Stop A Process?

kill pid.

23. How Do You Find Out About All Running Processes?

     ps -ag.

24. How Do You Stop All The Processes, Except The Shell Window?

     kill 0.

25. How Do You Define A Function In A Shell Script?

    function-narne() { #some code here return }.

26. How Do You Read Keyboard Input In Shell Scripts?

read { variable-name}.

27. How Does A Case Statement Look In Shell Scripts?

     case { variable} in {possible-value-1} {statement} ;; {possible-value-2}) {statement};;      esac.

28. How Do You Write A While Loop In Shell?

     while {condition} do {statement} done.

29. What Is Shell Scripting?

Shell scripting is used to program command line of an operating system. Shell Scripting is also used to program the shell which is the base for any operating system. Shell scripts often refer to programming UNIX. Shell scripting is mostly used to program operating systems of windows, UNIX, Apple, etc. Also this script is used by companies to develop their own operating system with their own features.

30. State The Advantages Of Shell Scripting?

There are many advantages of shell scripting some of them are, one can develop their own operating system with relevant features best suited to their organization than to rely on costly operating systems. Software applications can be designed according to their platform.

31. What Are The Disadvantages Of Shell Scripting?

·         There are many disadvantages of shell scripting they are

·         Design flaws can destroy the entire process and could prove a costly error.

·         Typing errors during the creation can delete the entire data as well as partition data.

·         Initially process is slow but can be improved.

·         Portbility between different operating system is a prime concern as it is very difficult to   port scripts etc.

32. Explain About The Slow Execution Speed Of Shells?

Major disadvantage of using shell scripting is slow execution of the scripts. This is because for every command a new process needs to be started. This slow down can be resolved by using pipeline and filter commands. A complex script takes much longer time than a normal script.

33. Give Some Situations Where Typing Error Can Destroy A Program?

There are many situations where typing errors can prove to be a real costly effort. For example a single extra space can convert the functionality of the program from deleting the sub directories to files deletion. cp, cn, cd all resemble the same but their actual functioning is different. Misdirected > can delete your data.

34. Explain About Return Code?

Return code is a common feature in shell programming. These return codes indicate whether a particular program or application has succeeded or failed during its process. && can be used in return code to indicate which application needs to be executed first.

35. What Are The Different Variables Present In Linux Shell?

 

Variables can be defined by the programmer or developer they specify the location of a particular variable in the memory. There are two types of shells they are System variables and user defined variables. System variables are defined by the system and user defined variables are to be defined by the user (small letters).

36. Explain About Gui Scripting?

  Graphical user interface provided the much needed thrust for controlling a computer and its applications. This form of language simplified repetitive actions. Support for different applications mostly depends upon the operating system. These interact with menus, buttons, etc.

 

37. Explain About Echo Command?

Echo command is used to display the value of a variable. There are many different options give different outputs such as usage c suppress a trailing line, r returns a carriage line, -e enables interpretation, r returns the carriage.

38. Explain About Stdin, Stdout And Stderr?

These are known as standard input, output and error. These are categorized as 0, 1 and 2. Each of these functions has a particular role and should accordingly functions for efficient output. Any mismatch among these three could result in a major failure of the shell.

39. Explain About Sourcing Commands?

Sourcing commands help you to execute the scripts within the scripts. For example sh command makes your program to run as a separate shell. .command makes your program to run within the shell. This is an important command for beginners and for special purposes.

40. Explain About Debugging?

Shell can make your debugging process easier because it has lots of commands to perform the function. For example sh –n command helps you to perform debugging. It helps you to read the shell but not to execute it during the course. Similarly sh –x command helps you by displaying the arguments and functions as they are executed.

41. Explain About Login Shell?

Login shell is very useful as it creates an environment which is very useful to create the default parameters. It consists of two files they are profile files and shell rc files. These files initialize the login and non login files. Environment variables are created by Login shell.

42. Explain About Non-login Shell Files?

The non login shell files are initialized at the start and they are made to run to set up variables. Parameters and path can be set etc are some important functions. These files can be changed and also your own environment can be set. These functions are present in the root. It runs the profile each time you start the process.

 

43. Explain About Shebang?

Shebang is nothing but a # sign followed by an exclamation. This is visible at the top of the script and it is immediately followed by an exclamation. To avoid repetitive work each time developers use shebang. After assigning the shebang work we pass info to the interpreter.

44. Explain About The Exit Command?

Every program whether on UNIX or Linux should end at a certain point of time and successful completion of a program is denoted by the output 0. If the program gives an output other than 0 it defines that there has been some problem with the execution or termination of the problem. Whenever you are calling other function, exit command gets displayed.

45. Explore About Environment Variables?

Environment variables are set at the login time and every shell that starts from this shell gets a copy of the variable. When we export the variable it changes from an shell variable to an environment variable and these variables are initiated at the start of the shell

46. How Do You Read Keyboard Input In Shell Scripts?

This is the way to read values into your shell script variables from keyboard input.

     #!/bin/bash

read name

echo "Hello $name"

47. What Is The Difference Between Writing Code In Shell And Editor?

Code in the script (Shell is interpreted) as shell is a interpreter where as editor is not interpreter certain set of commands(predefined) are used to handle editor.

48. Write down syntax for all loops in shell scripting?

For loop :

for i in $( ls ); do

echo item: $i

done

 

While loop :

#!/bin/bash

COUNTER=0

while [ $COUNTER -lt 10 ]; do

echo The counter is $COUNTER

let COUNTER=COUNTER+1

done

Until loop :

#!/bin/bash

COUNTER=20

until [ $COUNTER -lt 10 ]; do

echo COUNTER $COUNTER

let COUNTER-=1

done

49.  What it means by #!/bin/sh or #!/bin/bash at beginning of every script?

That line tells which shell to use. #!/bin/bash script to execute using /bin/bash. In case of python script there will be #!/usr/bin/python.

50.  What command “export” do?

Makes variable public in subshells.

51. How to run the script in the background ?

add “&” to the end of the script.

52. What “chmod 500 script” do?

Makes script executable for script owner.

53.  What “>” do?

Redirects output stream to file or another stream.

54. What difference between & and &&

& – we use it when we want to put the script to background
&& – when we want to execute command/script if the first script was finished successfully

55. When we need “if” before [ condition]?

When we need to run several commands if condition meets.

 

56. What would be the output of the command: name=John && echo ‘My name is $name’

My name is $name

 

57. Which is the symbol used for comments in bash shell scripting?

#

58. What would be the output of command: echo ${new:-variable}

   variable

59. What difference between ‘ and “quotes?

·          – we use it when do not want to evaluate variables to the values.

·         ” – all variables will be evaluated and its values will be assigned instead.

60. How to print all arguments provided to the script ?

echo $*
or
echo $@

61. What difference between [ $a == $b ] and [ $a -eq $b ]

[ $a == $b ] – should be used for string comparison
[ $a -eq $b ] – should be used for number tests

62. What difference between = and ==

·         = – we using to assign value to variable.

·         == – we using for string comparison.

63. Write the command to test if $a greater than 12?

[ $a -gt 12 ]

64. Write the command to test if $b less or equal 12?

[ $b -le 12 ]

65. How to redirect stdout and stderr streams to log.txt file from the script inside?

Add "exec >log.txt 2>&1" as the first command in the script.

66. How to get part of string variable with echo command only?

echo ${variable:x:y}

x - start position

y - length

example:

variable="My name is Petras, and I am developer."

echo ${variable:11:6} # will display Petras

67. How to get home_dir with echo command only if string variable=”User:123:321:/home/dir” is given ?

echo ${variable#*:*:*:}

or

echo ${variable##*:}

68. How to get “User” from the string above?

echo ${variable%:*:*:*}

or

echo ${variable%%:*}

 

69. How to list users which UID less than 100 (awk)?

awk -F: ‘$3<100’ /etc/passwd.

70. Compare Numeric Operators

Operator

Syntax

Description

eq

INTEGER1 -eq INTEGER2

INTEGER1 is equal to INTEGER2

ge

INTEGER1 -ge INTEGER2

INTEGER1 is greater than or equal to INTEGER2

gt

INTEGER1 -gt INTEGER2

INTEGER1 is greater than INTEGER2

le

INTEGER1 -le INTEGER2

INTEGER1 is less than or equal to INTEGER2

lt

INTEGER1 -lt INTEGER2

INTEGER1 is less than INTEGER2

ne

INTEGER1 -ne INTEGER2

INTEGER1 is not equal to INTEGER2

 

71. Syntax to define array in bash?

array=(“Hi” “my” “name” “is”)

72. Print the first array element ?

echo ${array[0]}

73. Print all array elements ?

echo ${array[@]}

74. Print all array indexes syntax?

echo ${!array[@]}

75. Syntax to remove array element with id 123 ?

unset array[123]

76. Syntax to add new element to the array with id 1980 ?

array[1980]=”New_element”

 

77. What Is Shell Script And Why It Is Required?

A Shell Script is a text file that contains one or more commands. As a system administrator we often need to issue number of commands to accomplish the task, we can add these all commands together in a text file (Shell Script) to complete daily routine task.

78. What Is The Default Login Shell And How To Change Default Login Shell For A Specific User?

In Linux like Operating system “/bin/bash” is the default login shell which is assigned while user creation. We can change default shell using the “chsh” command.

Example is shown below:

# chsh <username> -s <new_default_shell>

# chsh linuxtechi -s /bin/sh

79. What Are The Different Type Of Variables Used In A Shell Script?

  In a shell script we can use two types of variables:

System defined variables

User defined variables

System defined variables are defined or created by Operating System (Linux) itself. These variables are generally defined in Capital Letters and can be viewed by “set” command.

User defined variables are created or defined by system users and the values of variables can be viewed by using the command “echo $<Name_of_Variable>”.

 

80. How To Redirect Both Standard Output And Standard Error To The Same Location?

There two methods to redirect std output and std error to the same location:

Method:1 2>&1 (# ls /usr/share/doc > out.txt 2>&1 )

Method:2 &> (# ls /usr/share/doc &> out.txt )

81. What Is The Syntax Of “nested If Statement” In Shell Scripting?

Basic Syntax is shown below:

if [ Condition ]

then

command1

command2

…..

else

if [ condition ]

then

command1

command2

….

else

command1

command2

…..

fi

fi

82. What Is The Use Of “$?” Sign In Shell Script?

While writing a shell script, if you want to check whether previous command is executed successfully or not, then we can use “$?” with if statement to check the exit status of previous command.

Basic example is shown below:

root@localhost:~# ls /usr/bin/shar

/usr/bin/shar

root@localhost:~# echo $

0

If exit status is 0 , then command is executed successfully

 

root@localhost:~# ls /usr/bin/share

 

ls: cannot access /usr/bin/share: No such file or directory

 

root@localhost:~# echo $

 

2

 

If the exit status is other than 0, then we can say command is not executed successfully.

 

83. How To Compare Numbers In Linux Shell Scripting?

Test command is used to compare numbers in if-then statement.

Example is shown below:

#! /bin/bash

x=10

y=20

if [ $x -gt $y ]

then

echo “x is greater than y”

else

echo “y is greater than x”

fi

84. What Is The Use Of Break Command?

The break command is a simple way to escape out of a loop in progress. We can use the break command to exit out from any loop, including while and until loops.

85. What Is The Use Of Continue Command In Shell Scripting?

The continue command is identical to break command except it causes the present iteration of the loop to exit, instead of the entire loop. Continue command is useful in some scenarios where error has occurred but we still want to execute the next commands of the loop.

86. Tell Me The Syntax Of “case Statement” In Linux Shell Scripting?

The basic syntax is shown below:

case word in

value1)

command1

command2

…..

last_command

!!

value2)

command1

command2

……

last_command

;;

esac

87. What Is The Basic Syntax Of While Loop In Shell Scripting?

Like the for loop, the while loop repeats its block of commands a number of times. Unlike the for loop, however, the while loop iterates until its while condition is no longer true.

The basic syntax is :

while [ test_condition ]

do

commands…

done

88. How To Make A Shell Script Executable?

Using the chmod command we can make a shell script executable.

Example is shown below :

# chmod a+x myscript.sh

89. What Is The Use Of “#!/bin/bash” ?

#!/bin/bash is the first of a shell script , known as shebang , where # symbol is called hash and ‘!’ is called as bang. It shows that command to be executed via /bin/bash.

90. What Is The Syntax Of For Loop In Shell Script?

Basic Syntax of for loop is given below:

for variables in list_of_items

do

command1

command2

….

last_command

done

91. How To Debug A Shell Script?

A shell script can be debug if we execute the script with ‘-x’ option ( sh -x myscript.sh). Another way to debug a shell script is by using ‘-nv’ option (sh -nv myscript.sh).

92. How Compare The Strings In Shell Script?

Test command is used to compare the text strings. The test command compares text strings by comparing each character in each string.

93. What Are The Special Variables Set By Bourne Shell For Command Line Arguments?

The following table lists the special variables set by the Bourne shell for command line arguments.

Special Variables: Holds

$0: Name of the Script from the command line

$1: First Command-line argument

$2: Second Command-line argument

…..

…….

$9: Ninth Command line argument

$#: Number of Command line arguments

$*: All Command-line arguments, separated with spaces

94. How To Test Files In A Shell Script?

Test command is used to perform different test on the files. Basic test are listed below:

Test: Usage

 

-d file_name: Returns true if the file exists and is a directory.

-e file_name: Returns true if the file exists.

-f file_name: Returns true if the file exists and is a regular file.

-r file_name: Returns true if the file exists and have read permissions.

-s file_name: Returns true if the file exists and is not empty.

-w file_name: Returns true if the file exists and have write permissions.

-x file_name: Returns true if the file exists and have execute permissions.

95. How To Put Comments In Your Shell Script?

Comments are the messages to yourself and for other users that describe what a script is supposed to do and how its works. To put comments in your script, start each comment line with a hash sign (#).

 

Example is shown below:

 

#!/bin/bash

 

# This is a command

 

echo “I am logged in as $USER”

96. How To Get Input From The Terminal For Shell Script?

read’ command reads in data from the terminal (using keyboard). The read command takes in whatever the user types and places the text into the variable you name.

Example is shown below:

# vi /tmp/test.sh

#!/bin/bash

echo ‘Please enter your name’

read name

echo “My Name is $name”

# ./test.sh

Please enter your name

LinuxTechi

 

My Name is LinuxTechi

97. How To Unset Or De-assign Variables?

‘unset’ command is used to de-assign or unset a variable.

Syntax is shown below:

# unset <Name_of_Variable>

98. How To Perform Arithmetic Operation?

There are two ways to perform arithmetic operations:

Using expr command (# expr 5 + 2).

Using a dollar sign and square brackets ( $[ operation ] ) Example : test=$[16 + 4] ; test=$[16 + 4].

99. Basic Syntax Of Do-while Statement?

The do-while statement is similar to the while statement but performs the statements before checking the condition statement.

The following is the format for the do-while statement:

do

{

statements

} while (condition)

 

100.            How To Define Functions In Shell Scripting?

A function is simply a block of of code with a name. When we give a name to a block of code, we can then call that name in our script, and that block will be executed.

Example is shown below:$ disk usage () { df -h ; }

101.              How To Use Bc (bash Calculator) In A Shell Script?

Use the below Syntax to use bc in shell script.

Variable=`echo “options; expression” |

102.              Define Perl Scripting?

In the IT market, Perl scripting is considered as a robust scripting language which is used in various fields. Perl is good at obtaining Regular expressions and in all the fields of application it is unique. Perl is a scripting language which is based on interpreter but not on the languages based on compiler. In all the applications, optimization is used.

 

103.              Why To Use Perl Scripting?

Perl scripting is mainly used in functional concepts as well as regular expressions, you can also design own policies to obtain generalized pattern using regular expression. Perl is compatible or supports more than 76 operating systems and 3000 modules and it is known as Comprehensive Perl Archive Network modules.

 

104.              What Is Perl?

Perl is a programming language which is based on shell, C, Lisp, etc. In general, Perl is mainly used for network operations, OS program and for developing some websites.

105.              Why To Use Perl?

•           It is a powerful interpreter for free.

•           Perl is flexible and portable. It is very easy to learn Perl language.

106.              Why Do You Create An Application For Real Time System In Which Processing Speed Is Vital?

Perl is used in the following cases:

•     To process large text

•     When data manipulation is done by application

•     If you require fast developments expand to become libraries

•     To load database operations

107.              Which Is Your Favorite Module And Why It Is?

CGI.pm is my favorite module and it handles several tasks such as printing the headers, parsing the form input and it handles sessions and cookies effectively.

108.              How Perl Warnings Are Turn On And Why Is It Important?

In general, Perl excuse strange and also wrong code sometimes. Thus, the time spent for searching weird results and bugs in very high. You can identify common mistakes and strange places in the code easily when warnings are turned on. In the long run, the time required for debugging is saved a lot. There are numerous ways to turn on the warnings of Perl:

-w option is used on the command line for Perl one-liner

-w option on shebang line is used on windows or UNIX. Windows Perl interpreter do not require it.

For other systems, compiler documentation is checked or compiler warnings are selected.

109.              Differentiate Use And Require?

Use:

This method is used for modules.

The objects which are included are varied at compilation time.

You need not give a file extension.

Require:

This method is used for both modules and libraries.

The objects are included are verified at run time.

You need not give file extension.

110.      Distinguish My And Local?

The variables which are declared using “my” lives only in that particular block ion which they are declared and inherited functions do not have a visibility that are called in that block. The variables which are defined as “local” are visible in that block and they have a visibility in functions which are called in that particular block.

111.               Why Perl Patterns Are Not Regular Expressions?

   Perl patterns have back references

By the definition, a regular expression should determine next state infinite automation without extra money to keep in previous state. State machine is required by the pattern / ([ab] +) c1/ to remember old states. Such patterns are disqualified as being regular expressions in the term’s classic sense.

112.              What Happens If A Reference Is Returned To Private Variable?

Your variables are kept on track by the Perl, whether dynamic or else, and does not free things before you use them.

113.              Define Scalar Data And Variables?

The concept of data types is flexible, which is present in Perl. Scalar is a single thing such as a string or a number. The java concepts such as int, float, string, and double are similar to scalar concept of Perl. Strings and numbers are exchangeable. Scalar variable is nothing but a Perl variable which is used to store scalar data. A dollar sign $ is used by it which is followed by underscores or alphanumeric characters. It is a case sensitive.

114.              Why -w Argument Is Used With Perl Programs?

-w option of the interpreter is used by most of the Perl developers especially in the development stage of an application. It is warning option to turn on multiple warning messages that are useful in understanding and debugging the application.

115.              Which Has Highest Precedence In Between List And Terms? Explain?

In Perl, the highest precedence is for Perl. Quotes, variables, expressions in parenthesis are included in the Terms. The same level of precedence as Terms is for List operators. Especially, these operators have strong left word precedence.

116.              Define A Short Circuit Operator?

The C-style operator ll carries out logical operation which is used to tie logical clauses, overall value of true is returned if either clause is true. This operator is known as short-circuit operator because you need not check or evaluate right operand if the left operand is true.

117.              In Perl, Name Different Forms Of Goto And Explain?

In Perl, there are three different forms for goto, they are:

•     goto name

•     goto label

•     goto expr

goto name is used along with subroutines, it is used only when it is required as it creates destruction in programs. It is the second form of label where Execution is transferred to a statement labeled LABEL using goto LABEL. The last label form is goto EXPR which expects EXPR to evaluate label.

118.              Can You Add Two Arrays Together?

Yes, it is possible to add two arrays together with a push function. A value or values to end of the array is added using push function. The values of list are pushed on to the end of an array using push function. Length of list is used to increase length of an array.

 

119.              How Shift Command Is Used?

The first value of an array shifted using shift array function and it is returned, which results in array shortening by one element and moves everything from a place to left. If an array is not specified to shift, shift uses @ ARGV, the command line arguments of an array is passed to script or to an array named @.

120.              Explain Different Types Of Eval Statements?

In general, there are two types of eval statements they are:

•     Eval BLOCK and

•     Eval EXPR

An expression is executed by eval EXPR and BLOCK is executed by eval BLOCK. Entire block is executed by eval block, BLOCK. When you want your code passed in expression then first one is used and to parse code in the block, second one is used.

 

121.      Describe Returning Values From Subroutines?

The value of last expression which is evaluated is the return value of subroutine or explicitly, a returned statement can be used to exit subroutine which specifies return value. This return value is evaluated in perfect content based on content of subroutine call.

122.              What Are The Two Different Types Of Data Perl Handles?

Perl handles two types of data they are

(i) Scalar Variables and

(ii) Lists

Scalar variables hold a single data item whereas lists hold multiple data items.

123.      What Are Scalar Variables?

Scalar variables are what many programming languages refer to as simple variables. They hold a single data item, a number, a string, or a perl reference. Scalars are called scalars to differentiate them from constructs that can hold more than one item, like arrays.

124.      Explain About Lists?

A list is a construct that associates data elements together and you can specify a list by enclosing those elements in parenthesis and separating them with commas. They could themselves be arrays, hashes or even other lists. Lists do not have a specific list data type.

125.              Name All The Prefix Dereferencer In Perl?

The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.

(i) $-Scalar variables

(ii) %-Hash variables

(iii) @-arrays

(iv) &-subroutines

(v) Type globs-*myvar stands for @myvar, %myvar.

 

126.      Explain About An Ivalue?

An ivalue is an item that can serve as the target of an assignment. The term I value originally meant a “left value”, which is to say a value that appears on the left. An ivalue usually represents a data space in memory and you can store data using the ivalues name. Any variable can serve as an ivalue.

127.              How Does A "grep" Function Perform?

Grep returns the number of lines the expression is true. Grep returns a sub list of a list for which a specific criterion is true. This function often involves pattern matching. It modifies the elements in the original list.

128.              Explain About Typeglobs?

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.

129.      Is There Any Way To Add Two Arrays Together?

Of course you can add two arrays together by using push function. The push function adds a value or values to the end of an array. The push function pushes the values of list onto the end of the array. Length of an array can be increased by the length of list.

130.      How To Use The Command Shift?

Shift array function shifts off the first value of the array and returns it, thereby shortening the array by one element and moving everything from one place to the left. If you don’t specify an array to shift, shift uses @ ARGV, the array of command line arguments passed to the script or the array named @-.

131.              What Exactly Is Grooving And Shortening Of The Array?

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 nonexistent element in an array perl extends the array as needed, creating new elements. It also includes new elements in its array.

132.      What Are The Three Ways To Empty An Array?

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.

133.              How Do You Work With Array Slices?

An array slice is a section of an array that acts like a list, and you indicate what elements to put into the slice by using multiple array indexes in square brackets. By specifying the range operator you can also specify a slice.

134.              What Is Meant By Splicing Arrays Explain In Context Of List And Scalar.

Splicing an array means adding elements from a list to that array, possibly replacing elements now in the array. In list context, the splice function returns the elements removed from the array. In scalar context, the splice function returns the last element removed.

135.      What Are The Different Types Of Perl Operators?

There are four different types of perl operators they are

(i) Unary operator like the not operator

(ii) Binary operator like the addition operator

(iii) Tertiary operator like the conditional operator

(iv) List operator like the print operator

136.              Which Has The Highest Precedence, List Or Terms? Explain?

Terms have the highest precedence in perl. Terms include variables, quotes, expressions in parenthesis etc. List operators have the same level of precedence as terms. Specifically, these operators have very strong left word precedence.

137.              What Is Perl Scripting?

Perl Scripting is one of the robust scripting languages in the IT market which is being used in “n” of fields. Perl is rich in finding Regular expressions and stands unique in all fields of application.

PERL is a scripting language. Since all scripting languages are interpreter based languages but not compiler based languages, we use for optimization of code in all application.

138.      Why Do We Use Perl Scripting?

We use PERL scripting because it is rich in all regular expressions and functional concepts, we can create our own rules to find out particular generalized pattern by using regular expression. PERL supports or compatible in almost 76+ Operating systems and supports more than 3000 modules, called as CPAN (Comprehensive Perl Archive Network) modules.

139.              What Is A Subroutine?

Subroutine is perl is a block of code specially combined/grouped to perform a particular task.Which can be called at any point of time in a perl program.

Advantage using Subroutine

a) helps in modular programming making it easier to understand and maintain.

b)eliminates duplication by reusing the same code/calling the subroutine.

140.      Name An Instance You Used In Cpan Module?

CGI, DBI etc are very common packages used from CPAN. there are thousands of other useful modules.

141.              I Have A Variable Named $objref Which Is Defined In Main Package. I Want To Make It As A Object Of Class Xyz. How Could I Do It?

use XYZ;

my $objref= XYZ->new();

142.              What Is Meant 'die' In A Perl Program?

If the condition defined before the DIE statement is NOT met, the script will stop execution at that point, printing out the default error, if a custom error message is not defined.

143.              What Is Hash In Perl?

Hash in basically used to comment the script line.

A hash is and unordered set of key/value pairs that you access using strings (keys) as subscripts, to look up the scalar value corresponding to a given key.

144.              What Does This Mean :

'$_' ?

Default variable in Perl.

Its an Default variable in Perl, where the input from the user will be taken into this variable if the variable is not defined by the user.

145.              What Is A Datahash(). What Does It Mean? And For What Purpose It Is Used??

In Win32::ODBC, DataHash() function is used to get the data fetched through the sql statement in a hash format.

146.              Explain About Returning Values From Subroutines (functions)?

The return value of the subroutine is the value of the last expression evaluated or you can explicitly use a return statement to exit the subroutine specifying the return value. That return value is evaluated in the appropriate content depending on the content of the subroutine call.

147.      What Is Meant By A 'pack' In Perl?

Pack Converts a list into a binary representation

Takes an array or list of values and packs it into a binary structure, returning the string containing the structure

Hope that kills the problem

148.              How Do You Connect To Database In Perl

There is DBI module. use DBI;my $dbh = DBI->connect('dbi:Oracle:orcl', 'username', 'password',)where username and password is yours. This is example for oracle database.

For Sybase:

use DBI;

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

 

149.      What Is A Short Circuit Operator?

The C-Style operator, ll, performs a logical (or) operation and you can use it to tie logical clauses together, returning an overall value of true if either clause is true. This operator is called a short-circuit operator because if the left operand is true the right operand is not checked or evaluated.

 

150.      How To Connect With Sqlserver From Perl And How To Display Database Table Info?

There is a module in perl named DBI - Database independent interface which will be used to connect to any database by using same code. Along with DBI we should use database specific module here it is SQL server. for MSaccess it is DBD::ODBC, for MySQL it is DBD::mysql driver, for integrating oracle with perl use DBD::oracle driver is used. IIy for SQL server there are available many custom defined ppm( perl package manager) like Win32::ODBC, mssql::oleDB etc.so, together with DBI, mssql::oleDB we can access SQL server database from perl. The commands to access database is same for any database.

151.      What Value Is Returned By A Lone Return; Statement?

The undefined value in scalar context, and the empty list value () in list context. This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.

152.      How To Turn On Perl Warnings? Why Is That Important?

Perl is very forgiving of strange and sometimes wrong code, which can mean hours spent searching for bugs and weird results. Turning on warnings helps uncover common mistakes and strange places and save a lot of debugging time in the long run. There are various ways of turning on Perlwarnings:

* For Perl one-liner, use -w option on the command line.

* On Unix or Windows, use the -w option in the shebang line (The first # line in the script). Note: Windows Perl interpreter may not require it.

* For other systems, choose compiler warnings, or check compiler documentation.

153.      Write A Script To Reverse A String Without Using Perl's Built In Functions?

my $txt = 'Hello World';

my $len= length($txt);

my $rev;

while($len > 0){

$len--;

$rev .= substr($txt,$len,1);

}

print $txt, ' - Reversed = ' , $rev;

154.              What Is Perl One-liner?

There are two ways a Perl script can be run:

--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: %gt perl -e "print "Hello";". One-liner doesn't mean one Perl statement. One-liner may contain many statements in one line.

--from a script file, called Perl program.

155.              What Are The Different Types Of Eval Statements?

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.

156.              What Is Your Experience Of Interfacing Perl To Database?

The correct answer is DBI

157.              What Is Cpan ? What Are The Modules Coming Under This?

CPAN is Comprehensive Perl Archive Network. It’s a repository contains thousands of Perl modules, source and documentation, and all under GNU/GPL or similar license. Some Linux distributions provide a tool named "cpan" with which you can install packages directly from CPAN

158.              Given A File, Count The Word Occurrence (case Insensitive)?

open(FILE,"filename");

@array=; $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";

159.      How Do I Set Environment Variables In Perl Programs?

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';

160.              Why We Use Perl?

1.Perl is a powerful free interpreter.

2.Perl is portable, flexible and easy to learn.

-For shell scripting

-For CGI

-Tons of scripts are available.

-Easy development

-Enormous big support script archive like CPAN

-No one starts to write a Perl scripts from scratch, you choose one from an archive and modify that.

-It is a "mature" scripting language.

-You may find Perl interpreter on every mission critical environment

-Easy to learn

161.      Why Does Perl Not Have Overloaded Functions?

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 want array(), 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.