Download - Unix Scripting&Perl

Transcript
Page 1: Unix Scripting&Perl

Shell Scripting Interview Questions

1) 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.

2) 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.

3) 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.

4) 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.

5) 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.Coding Related Shell Scripting Interview Questions ...

6) 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.

7) 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).

8) Explain about GUI scripting?

Page 2: Unix Scripting&Perl

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.Shell Scripting Command Interview Questions ...

9) 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.

10) 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.

11) 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.

12) Explain about debugging?Shell can make your debugging process easier because it has lots of commands to perform the function. For example sh –ncommand 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.

13) 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.

14) 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.

15) 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.

16) 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.

Page 3: Unix Scripting&Perl

Whenever you are calling other function, exit command gets displayed.

17) 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.

1. Construct pipes to execute the following jobs.

1. Output of who should be displayed on the screen with value of total number of users who have logged indisplayed at the bottom of the list.2. Output of ls should be displayed on the screen and from this output the lines containing the word ‘poem’should be counted and the count should be stored in a file.3. Contents of file1 and file2 should be displayed on the screen and this output should be appended in a file.From output of ls the lines containing ‘poem’ should be displayed on the screen along with the count.4. Name of cities should be accepted from the keyboard . This list should be combined with the list presentin a file. This combined list should be sorted and the sorted listshould be stored in a file ‘newcity’.5. All files present in a directory dir1 should be deleted any error while deleting should be stored in a file‘errorlog’.

2. Explain the following commands.

$ ls > file1$ banner hi-fi > message$ cat par.3 par.4 par.5 >> report$ cat file1>file1$ date ; who$ date ; who > logfile$ (date ; who) > logfile

3. What is the significance of the “tee” command?

It reads the standard input and sends it to the standard output while redirecting a copy of what it has read tothe file specified by the user.4. What does the command “ $who | sort –logfile > newfile” do?

Page 4: Unix Scripting&Perl

The input from a pipe can be combined with the input from a file . The trick is to use the special symbol “-“(a hyphen) for those commands that recognize the hyphen as std input.In the above command the output from who becomes the std input to sort , meanwhile sort opens the filelogfile, the contents of this file is sorted together with the output of who (rep by the hyphen) and the sortedoutput is redirected to the file newfile.5. What does the command “$ls | wc –l > file1” do?

ls becomes the input to wc which counts the number of lines it receives as input and instead of displayingthis count , the value is stored in file1.

6. Which of the following commands is not a filter man , (b) cat , © pg , (d) head

Ans: manA filter is a program which can receive a flow of data from std input, process (or filter) it and send the resultto the std output.7. How is the command “$cat file2 “ different from “$cat >file2 and >> redirection operators ?is the output redirection operator when used it overwrites while >> operator appends into the file.8. Explain the steps that a shell follows while processing a command.After the command line is terminated by the key, the shel goes ahead with processing the command line inone or more passes. The sequence is well defined and assumes the following order.Parsing: The shell first breaks up the command line into words, using spaces and the delimiters, unlessquoted. All consecutive occurrences of a space or tab are replaced here with a single space.Variable evaluation: All words preceded by a $ are avaluated as variables, unless quoted or escaped.Command substitution: Any command surrounded by backquotes is executed by the shell which thenreplaces the standard output of the command into the command line.Wild-card interpretation: The shell finally scans the command line for wild-cards (the characters *, ?, [, ]).Any word containing a wild-card is replaced by a sorted list offilenames that match the pattern. The list of these filenames then forms the arguments to the command.PATH evaluation: It finally looks for the PATH variable to determine the sequence of directories it has tosearch in order to hunt for the command.9. What difference between cmp and diff commands?cmp - Compares two files byte by byte and displays the first mismatch

Page 5: Unix Scripting&Perl

diff - tells the changes to be made to make the files identical10. What is the use of ‘grep’ command?‘grep’ is a pattern search command. It searches for the pattern, specified in the command line withappropriate option, in a file(s).Syntax : grepExample : grep 99mx mcafile11. What is the difference between cat and more command?Cat displays file contents. If the file is large the contents scroll off the screen before we view it. Socommand 'more' is like a pager which displays the contents page by page.12. Write a command to kill the last background job?Kill $!13. Which command is used to delete all files in the current directory and all its sub-directories?rm -r *14. Write a command to display a file’s contents in various formats?$od -cbd file_namec - character, b - binary (octal), d-decimal, od=Octal Dump.15. What will the following command do?$ echo *It is similar to 'ls' command and displays all the files in the current directory.16. Is it possible to create new a file system in UNIX?Yes, ‘mkfs’ is used to create a new file system.17. Is it possible to restrict incoming message?Yes, using the ‘mesg’ command.18. What is the use of the command "ls -x chapter[1-5]"ls stands for list; so it displays the list of the files that starts with 'chapter' with suffix '1' to '5', chapter1,chapter2, and so on.19. Is ‘du’ a command? If so, what is its use?Yes, it stands for ‘disk usage’. With the help of this command you can find the disk capacity and free spaceof the disk.20. Is it possible to count number char, line in a file; if so, How?Yes, wc-stands for word count.wc -c for counting number of characters in a file.wc -l for counting lines in a file.21. Name the data structure used to maintain file identification?‘inode’, each file has a separate inode and a unique inode number.22. How many prompts are available in a UNIX system?Two prompts, PS1 (Primary Prompt), PS2 (Secondary Prompt).23. How does the kernel differentiate device files and ordinary files?Kernel checks 'type' field in the file's inode structure.24. How to switch to a super user status to gain privileges?Use ‘su’ command. The system asks for password and when valid entry is made the user gains

Page 6: Unix Scripting&Perl

super user(admin) privileges.25. What are shell variables?Shell variables are special variables, a name-value pair created and maintained by the shell.Example: PATH, HOME, MAIL and TERM26. What is redirection?Directing the flow of data to the file or from the file for input or output.Example : ls > wc27. How to terminate a process which is running and the specialty on command kill 0?With the help of kill command we can terminate the process.Syntax: kill pidKill 0 - kills all processes in your system except the login shell.28. What is a pipe and give an example?A pipe is two or more commands separated by pipe char '|'. That tells the shell to arrange for the output ofthe preceding command to be passed as input to the following command.Example : ls -l | prThe output for a command ls is the standard input of pr.When a sequence of commands are combined using pipe, then it is called pipeline.29. Explain kill() and its possible return values.There are four possible results from this call:‘kill()’ returns 0. This implies that a process exists with the given PID, and the system would allow you tosend signals to it. It is system-dependent whether the process could be a zombie.‘kill()’ returns -1, ‘errno == ESRCH’ either no process exists with the given PID, or security enhancementsare causing the system to deny its existence. (On some systems, the process could be a zombie.)‘kill()’ returns -1, ‘errno == EPERM’ the system would not allow you to kill the specified process. This meansthat either the process exists (again, it could be a zombie) or draconian security enhancements are present(e.g. your process is not allowed to send signals to *anybody*).‘kill()’ returns -1, with some other value of ‘errno’ you are in trouble! The most-used technique is to assumethat success or failure with ‘EPERM’ implies that the process exists, and any other error implies that itdoesn't.An alternative exists, if you are writing specifically for a system (or all those systems) that provide a ‘/proc’filesystem: checking for the existence of ‘/proc/PID’ may work.

30. What is relative path and absolute path.Absolute path : Exact path from root directory.Relative path : Relative to the current path.

Page 7: Unix Scripting&Perl

Unix Commands Interview Questions

1) State and explain about features of UNIX?UNIX operating system originally was developed in 1969. This is an open source operating system developed by AT&T. It is widely used in work stations and servers. It is designed to be multi tasking, multi user and portable. UNIX has many several components packed together.

2) Explain about sh?Sh is the command line interpreter and it is the primary user interface. This forms the programmable command line interpreter. After windows appeared it still retained the programmable characteristics.

3) Explain about system and user utilities?There are two utilities they are system and user utilities. System utilities contain administrative tools such as mkfs, fsck, etc. Where as user utilities contain features such as passwd, kill, etc. It basically contains environment values.

4) Explain about document formatting?UNIX systems were primarily used for typesetting systems and document formatting. Modern UNIX systems used packages such as Tex and Ghostscript. It uses some of the programs such as nroff, tbl, troff, refer, eqn and pic. Document formatting is very used because it forms the base of UNIX.

5) Explain about communication features in UNIX?Early UNIX systems used inter user communication programs mail and write commands. They never contained a fully embedded inter user communication features. Systems with BSD included TCP/IP protocols.

6) Explain about chmod options filename?This command allows you to change, write, read and execute permissions on your file. Changes can be done to the file system but at times you need to change permissions for the file systems. At times files should be executable for viewing the files.

7) Explain about gzip filename?Gzip filename is used to compress the files so that those files take up less space. The size of the file actually gets reduced to half their size but they might also depend upon about the file size and nature of the file systems. Files using gzip file name end with .gz.

8) Explain about refer?Refer was written in Bell Laboratories and it is implemented as a troff preprocessor. This program is used managing bibliographic references and it is used to cite them in troff documents. It is offered in most of the UNIX packages. It refers with text and reference file.

9) Explain about lpr filename?This command is used to print a file. If you want to change the default print you can change the

Page 8: Unix Scripting&Perl

printer by using the P option. For double sided print you can use lpr-Pvalkyr-d. This is very useful command in UNIX present in many packages.

10) Explain about lprm job number?This command is used to remove documents from the printer queue. The job number or the queue number can be found by using lpq. Printer name should be specified but this is not necessary if you want to use your default printer.

11) Brief about the command ff?This command finds files present anywhere on the system. This command is used to find document location where you forgot the directory in which you kept the file but you do remember about the name. This command is not restricted in finding files it displays files and documents relevant to the name.

12) Brief about finger username?This command is used to give information about the user; it gives out a profile about the user. This command is very useful for administrators as it gives the log information, email, current log information, etc. finger also displays information such as phone number and name when they use a file called .plan.

13) Explain about the command elm?This command lets you to send email message from your system. This command is not the only one which sends email there are lots of other messenger systems which can facilitate the process of sending a mail. This command behaves differently on different machines.

14) Brief about the command kill PID?This command ends the process to which it was assigned (ID). This command cannot be used in multi systems in the network. ID can be obtained by the command ps. This command ignores completely the state at which the process is it kills the process.

15) Explain about the command lynx?This command helps you to browse web from an ordinary terminal. Text can be seen but not the pictures. URL can be assigned as an argument to the G command. Help section can be obtained by pressing H and Q makes the program to quit.

16) Brief about the command nn?This command allows you to read the news. First you can read about the local news and then the remote news. "nnl” command makes or allows you to read local news and nnr command is used to read remote news. Manual and help information is available with many popular packages.

17) Brief about ftp hostname?This command lets you download information, documents, etc from a remote ftp. First it is important to configure an FTP for the process to begin. Some of the important commands relevant to the usage of FTP are as follows get, put, mget, mput, etc. If you are planning to transfer files other than ASCII defined it is imperative to use binary mode

Page 9: Unix Scripting&Perl

Shell Scripting Interview Questions

1) 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.

2) 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.

3) 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.

4) 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.

5) 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.Coding Related Shell Scripting Interview Questions ...

6) 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.

7) 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).

Page 10: Unix Scripting&Perl

8) 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.Shell Scripting Command Interview Questions ...

9) 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.

10) 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.

11) 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.

12) Explain about debugging?Shell can make your debugging process easier because it has lots of commands to perform the function. For example sh –ncommand 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.

13) 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.

14) 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.

15) 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.

16) Explain about the Exit command?Every program whether on UNIX or Linux should end at a certain point of time and successful

Page 11: Unix Scripting&Perl

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.

17) 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.

UNIX INTERVIEW QUESTIONS

I’ve put together a document here to use to evaluate someone’s UNIX knowledge. You can freely use and distribute this document providing it is in accordance with the TFS © Policy on our main page.

Level I

How can you tell what shell you are running on a UNIX system?

Answer :You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.What are conditions on which deadlock can occur while swapping the processes?Answer :All processes in the main memory are asleep. All ‘ready-to-run’ processes are swapped out.There is no space in the swap device for the new incoming process that are swapped out of the main memory. There is no space in the main memory for the new incoming process. How do you change File Access Permissions?Answer :Every file has following attributes:owner’s user ID ( 16 bit integer )owner’s group ID ( 16 bit integer )File access mode word‘r w x -r w x- r w x’(user permission-group permission-others permission)r-read, w-write, x-executeTo change the access mode, we use chmod(filename,mode).Example:To change mode of myfile to ‘rw-rw-r–’ (ie. read, write permission for user - read,write permission for group - only read permission for others) we give the args as:chmod(myfile,0664) .Each operation is represented by discrete values‘r’ is 4‘w’ is 2

Page 12: Unix Scripting&Perl

‘x’ is 1Therefore, for ‘rw’ the value is 6(4+2).Example 2:To change mode of myfile to ‘rwxr–r–’ we give the args as:chmod(myfile,0744). 

List the system calls used for process management.Answer :System calls Descriptionfork() To create a new processexec() To execute a new program in a processwait() To wait until a created process completes its executionexit() To exit from a process executiongetpid() To get a process identifier of the current processgetppid() To get parent process identifiernice() To bias the existing priority of a processbrk() To increase/decrease the data segment size of a process 

What is the difference between Swapping and Paging?

Answer :

Swapping:Whole process is moved from the swap device to the main memory for execution. Process size must be less than or equal to the available main memory. It is easier to implementation and overhead to the system. Swapping systems does not handle the memory more flexibly as compared to the paging systems.

Paging:Only the required memory pages are moved to main memory from the swap device for execution. Process size does not matter. Gives the concept of the virtual memory.

It provides greater flexibility in mapping the virtual address space into the physical memory of the machine. Allows more number of processes to fit in the main memory simultaneously. Allows the greater process size than the available physical memory. Demand paging systems handle the memory more flexibly.

What is the difference between cmp and diff commands?Answer :

cmp - Compares two files byte by byte and displays the first mismatchdiff - tells the changes to be made to make the files identical

Page 13: Unix Scripting&Perl

What is meant by the nice value?Answer :

Nice value is the value that controls {increments or decrements} the priority of the process. This value that is returned by the nice () system call. The equation for using nice value is:Priority = (“recent CPU usage”/constant) + (base- priority) + (nice value)Only the administrator can supply the nice value. The nice () system call works for the running process only. Nice value of one process cannot affect the nice value of the other process. 

What is a daemon?Answer :A daemon is a process that detaches itself from the terminal and runs, disconnected, in the background, waiting for requests and responding to them. It can also be defined as the background process that does not belong to a terminal session. Many system functions are commonly performed by daemons, including the sendmail daemon, which handles mail, and the NNTP daemon, which handles USENET news. Many other daemons may exist. Some of the most common daemons are:init: Takes over the basic running of the system when the kernel has finished the boot process.inetd: Responsible for starting network services that do not have their own stand-alone daemons. For example, inetd usually takes care of incoming rlogin, telnet, and ftp connections.cron: Responsible for running repetitive tasks on a regular schedule.

What are the process states in UNIX?Answer :As a process executes it changes state according to its circumstances. Unix processes have the following states:Running : The process is either running or it is ready to run .Waiting : The process is waiting for an event or for a resource.Stopped : The process has been stopped, usually by receiving a signal.Zombie : The process is dead but have not been removed from the process table.

Perl

 1. How do you know the reference of a variable whether it is a reference,scaller, hash or array?Ans: there is a 'ref' function that lets you know2. what is the difference between 'use' and 'require' function?Ans: Use: 1. the method is used only for modules (only to include .pm type file) 2. theincluded object are verified at the time of compilation. 3. No Need to give file extentsion.Require: 1. The method is used for both libraries ( package ) and modules 2. The includeobjects are varified at the run time. 3. Need to give file Extension.3. What is the use of 'chomp' ? what is the difference between 'chomp' and 'chop'?Ans. 'chop' functiononly removes the last character completely 'from the scaler, where as'chomp' function only removes the last character if it is a newline. by default, chomp onlyremoves what is currently defined as the $INPUT_RECORD_SEPARATOR. whenever you call 'chomp ', it

Page 14: Unix Scripting&Perl

checks the value of a special variable '$/'. whatever the value of '$/' iseliminated from the scaler. by default the value of '$/' is 'n'4. Print this array @arr in reversed case-insensitive order Ans> @solution = sort {lc $a comp lc$b } @arr.5. What is '->' in Perl?Ans. it is a symbolic link to link one file name to a new name. so lets say we do it likefile1-> file2, if we read file1, we end up reading file2.6. how do you check the return code of system call?Ans. System calls "traditionally" returns 9 when successful and 1 when it fails. system(cmd) or die "Error in command";7. #create directory if not thereif (! -s "$temp/engl_2/wf"){ System "mkdir -p $temp/engl_2/wf"; } if (! -s"$temp/backup_basedir"){ system "mkdir -p $temp/backup_basedir"; } ${pack_2} = -M 

"${temp}/engl_2/wf/${wf_package_name}.data"; ${new_pack}= -M"{pack}/package.data"; What is the use of -M and -s in the above script?Ans. -s means is filename a non-empty file -M

how long since filename modified?8. How to substitute a particular string in a file containing million of record?Ans. perl -p -ibak -e

's/search_str/replace_str/g' filename9. I have a variable named $objref which is defined in main package. I want to make it asa

Object of class XYZ. how could I do it?Ans. use XYZ my $objref =XYZ -> new() OR, bless $objref, 'XYZ';

10. what is meant by a 'pack' in perl?Ans. 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 It takes aLIST of values and converts it into a string. The string contaings a con-catenation of theconverted values. Typically, each converted values looks like its machine-

levelrepesentation. for example, on 32-bit machines a converted integer may be representated by a sequence of 4 bytes.

11. how to implement stack in Perl?Ans. through push() and shift() function. push adds the element at the last of array andshift() removes from the beginning of an array.

12. What is Grep used for in Perl?Ans. Grep is used with regular expression to check if a parituclar value exist in an array.it returns 0 it the value does not exists, 1 otherwise.

13. How to code in Perl to implement the tail function in unix?And. You have to maintain a structure to store the line number and the size of the file atthat time eg. 1-10bytes, 2-18bytes..

you have a counter to increase the number of lines tofind out the number of lines in the file. once you are through the file, you will know thesize of the file at any nth line, use 'sysseek' to move

the file pointer back to that position(last 10) and thens tart reading till the end.

 14. Explain the difference between 'my' and 'local' variable scope declarations?Ans. Both of them are used to declare local variables. The variables declared with 'my'can live only within the block and cannot gets its visibility inherited fucntions calledwithin that block, but one defined as 'local' canlive within the block and have its visibilityin the functions called within that block.15. How do you navigate thorugh an XML documents?Ans. You can use the XML::DOM navigation methods to navigate thorugh anXML::DOM node tree and use the getnodevalue to recover the data. DOM Parser is usedwhen it is neede to do node operation. Instead we may use SAX parser if you requiresimple processing of the xml structure.

Page 15: Unix Scripting&Perl

16. How to delete an entire directory containing few files in the directory?Ans. rmtree($dir); OR, you can use CPAN module File::Remove Though it sounds likedeleting file but it can be used also for deleting directories. &File::Removes::remove(1,$feed-dir,$item_dir);17. What are the arguements we normally use for Perl Interpreter Ans. -e for Execute, -c to compile, -d to call the debugger on the file specified, -T for traint mode for security/input checking -W for show all warning mode (or -w to showless warning)18. what is it meants by '$_'?Ans. it is a default variable which holds automatically, a list of arguements passed to thesubroutine within parentheses.19. How to connect to sql server through Perl?Ans. We use the DBI(Database Independent Interface) module to connect to anydatabase. use DBI; $dh = DBI->connect("dbi:mysql:database=DBname","username","password"); $sth = $dh-> prepare("select name, symbol from table"); $sth->execute(); while(@row = $sth->fetchrow_array()){ print "name =$row[0].symbol= $row[1]; } $dh->disconnect $dh=DBI->connect("dbi:mysql")20. What is the purpose of -w,strict and -T?Ans. -w option enables warning - strict pragma is used when you should declare variables before their use -T is taint mode. TAint mode makes a program more secure by keepingtrack of arguments which are passed from external source.21. What is the difference between die and exit?Ans. Die prints out stderr message in the terminal before exiting the program while exit just terminate the program without giving any message. Die also can evaluate expressions before exiting.22. where do you go for perl help?Ans. perldoc command with -f option is the best. i also go to search.cpan.org for help.23. what is the Tk module?Ans. it provides a GUI interface24. what is your favorite module in Perl?Ans. CGI and DBI. CGI(Common Gateway Interface) because we do not need to worryabout the subtle features of form processing.25. What is hash in perl?Ans. A hash is like an associative array, in that it is a collection of scalar data, withindividual elements selected by some index value which essentially are scallars andcalled as keys. Each key corresponds to some value. Hashes are represented by %followed by some name.26.what does 'qw()' mean? what's the use of it?Ans. qw is a construct which quotes words delimited by spaces. use it when you havelong list of words that are nto quoted or youjust do not want to type those quotes asyoutype out a list of space delimited words. like @a = qw(1234) which is like@a=("1","2","3","4");27. what is the difference between Perl and shell script?Ans. whatever you can do in shell script can be done in Perl.however 1. Perl gives you anextended advantages of having enormous library. 2. you do not need to write everythingfrom scartch.28. what is stderr() in perl?Ans. special file handler to standard error in any package.29. what is a regular expression?Ans. it defines a pattern for a search to match.30. what is the difference between for and foreach?Ans. functionally, there is no difference between them.31, what is the difference between exec and system?Ans. exec runs the given process, switches to its name and never returns while systemforks off the given process, waits for its to complete and then return.32. What is CPAN?Ans. CPAN is comprehensive Perl Archive Network. its a repository contains thousandsof Perl Modules, source and documentation, and all under GNU/GPL or smilar

Page 16: Unix Scripting&Perl

licence.you can go to www.cpan.org for more details. Some linux distribution provide a tillnames 'cpan; which you can install packages directly from cpan.33. what does this symbol mean '->'?Ans. In Perl it is an infix dereference operator. for array subscript, or a hash key, or asubroutine, then the ihs must be a reference. can also be used as method invocation.34. what is a DataHash()Ans. in Win32::ODBC, DataHash() function is used to get the data fetched thorugh thesql statement in a hash format.35. what is the difference between C and Perl?Ans. make up36. Perl regular exp are greedy. what is it mean by that?Ans. it tries to match the longest string possible.37. what does the world '&my variable' mean?Ans. &myvariable is calling a sub-routine. & is used to indentify a subroutine.38, what is it meant by @ISA, @EXPORT, @EXPORT_0?Ans @ISA -> each package has its own @ISA array. this array keep track of classes it isinheriting. ex: package child; @ISA=( parentclass); @EXPORT this array stores thesubroutins to be exported from a module. @EXPORT_OK this array stores the subroutinsto be exported only on request.39.what package you use to create a windows services?ans. use Win32::OLE.40. How to start Perl in interactive mode?Ans. perl -e -d 1 PerlConsole.41. How do I set environment variables in Perl programs?Ans. you can just do something like this: $ENV{'PATH'} = '...'; As you may remember,"%ENV" is a special hash in Perl that contains the value of all your environmentvariables. Because %ENV is a hash, you can set environment variables just as you'd setthe value of any Perl hash variable. Here's how you can set your PATH variable to makesure the following four directories are in your path:: $ENV{'PATH'} ='/bin:/usr/bin:/usr/local/bin:/home/yourname/bin';42. what is the difference between C++ and Perl?Ans. Perl can have objects whose data cannot be accessed outside its class, but C++cannot. Perl can use closures with unreachable private data as objects, and C++ doesn'tsupport closures. Furthermore, C++ does support pointer arithmetic via `int *ip =(int*)&object', allowing you do look all over the object. Perl doesn't have pointer arithmetic. It also doesn't allow `#define private public' to change access rights to foreignobjects. On the other hand, once you start poking around in /dev/mem, no one is safe.43. How to open and read data files with Perl?Ans. Data files are opened in Perl using the open() function. When you open a data file,all you have to do is specify (a) a file handle and (b) the name of the file you want to readfrom. As an example, suppose you need to read some data from a file named"checkbook.txt". Here's a simple open statement that opens the checkbook file for readaccess: open (CHECKBOOK, "checkbook.txt"); In this example, the name"CHECKBOOK" is the file handle that you'll use later when reading from thecheckbook.txt data file. Any time you want to read data from the checkbook file, just usethe file handle named "CHECKBOOK". Now that we've opened the checkbook file, we'dlike to be able to read what's in it. Here's how to read one line of data from the checkbook file: $record = < CHECKBOOK > ; After this statement is executed, the variable $recordcontains the contents of the first line of the checkbook file. The "<>" symbol is called theline reading operator. To print every record of information from the checkbook file open(CHECKBOOK, "checkbook.txt") || die "couldn't open the file!"; while ($record = <CHECKBOOK >) { print $record; } close(CHECKBOOK);

Page 17: Unix Scripting&Perl

44. How do i do fill_in_the_blank for each file in a directory?Ans. #!/usr/bin/perl -w opendir(DIR, "."); @files = readdir(DIR); closedir(DIR); foreach$file (@files) { print "$file\n"; }45. how do i generate a list of all .html files in a directoryAns. here is a snippet of code that just prints a listing of every file in teh current directory.that ends with the entension #!/usr/bin/perl -w opendir(DIR, "."); @files =grep(/\.html$/,readdir(DIR)); closedir(DIR); foreach $file (@files) { print "$file\n"; }46. what is Perl one-liner?Ans. 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 Perlstatement. One-liner may contain many statements in one line. --from a script file, calledPerl program.47, Assume both a local($var) and a my($var) exist, what's the difference between ${var}and ${"var"}?Ans. ${var} is the lexical variable $var, and ${"var"} is the dynamic variable $var. Notethat because the second is a symbol table lookup, it is disallowed under `use strict "refs"'.The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), arevariously knows as private, lexical, or scoped variable.48. What happens when you return a reference to a private variable?ans. Perl keeps track of your variables, whether dynamic or otherwise, and doesn't freethings before you're done using them49. What are scalar data and scalar variables?Ans. Perl has a flexible concept of data types. Scalar means a single thing, like a number or string. So the Java concept of int, float, double and string equals to Perl\'s scalar inconcept and the numbers and strings are exchangeable. Scalar variable is a Perl variablethat is used to store scalar data. It uses a dollar sign $ and followed by one or moreaphanumeric characters or underscores. It is case sensitive.50. Assuming $_ contains HTML, which of the following substitutions will remove alltags in it?Ans. You can't do that. If it weren't for HTML comments, improperly formatted HTML,and tags with interesting data like < SCRIPT >, you could do this. Alas, you cannot. Ittakes a lot more smarts, and quite frankly, a real parser.51. I want users send data by formmail but when they send nothing or call it from web site they will see error. codes in PHP like this: if (isset($HTTP_POST_VARS)){ .......... }else{ echo ("error lalalalal") } How it will look in perl?Ans. In perl if ($ENV{'REQUEST_METHOD'} eq 'POST'){ ..... }52. What is the output of the following Perl program?1 $p1 = "prog1.java"; 2 $p1 =~ s/(.*)\.java/$1.cpp/; 3 print "$p1\n"; Ans. prog1.cpp53. Why aren't Perl's patterns regular expressions?Ans. Because Perl patterns have backreferences. A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extramemory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine toremember old states, and thus disqualifies such patterns as being regular expressions inthe classic sense of the term.54. What does Perl do if you try to exploit the execve(2) race involving setuid scripts?Ans. Sends mail to root and exits. It has been said that all programs advance to the pointof being able to automatically read mail. While not quite at that point (well, withouthaving a module loaded), Perl does at least automatically send it.

Page 18: Unix Scripting&Perl

55. How do I do < fill-in-the-blank > for each element in a hash?Ans. Here's a simple technique to process each element in a hash: #!/usr/bin/perl -w%days = ( 'Sun' =>'Sunday', 'Mon' => 'Monday', 'Tue' => 'Tuesday', 'Wed' =>'Wednesday', 'Thu' => 'Thursday', 'Fri' => 'Friday', 'Sat' => 'Saturday' ); foreach $key (sortkeys %days) { print "The long name for $key is $days{$key}.\n"; }57. How do I sort a hash by the hash key?Ans. Suppose we have a class of five students.Their names are kim, al, rocky, chrisy, and jane. Here's a test program that prints the contents of the grades hash, sorted by studentname: #!/usr/bin/perl -w %grades = ( kim => 96, al => 63, rocky => 87, chrisy => 96, jane => 79, ); print "\n\tGRADES SORTED BY STUDENT NAME:\n"; foreach $key(sort (keys(%grades))) { print "\t\t$key \t\t$grades{$key}\n"; } The output of this program looks like this: GRADES SORTED BY STUDENT NAME: al 63 chrisy 96 jane79 kim 96 rocky 87 }

58. How do you print out the next line from a filehandle with all its bytes reversed?Ans. print scalar reverse scalar Surprisingly enough, you have to put both the reverse andthe into scalar context separately for this to work.59. How do I send e-mail from a Perl/CGI program on a Unix system?Ans. Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We'll gothrough a quick example here.Assuming that you've already have e-mail information youneed, such as the send-to address and subject, you can use these next steps to generateand send the e-mail message: # the rest of your program is up here ... open(MAIL, "|/usr/lib/sendmail -t"); print MAIL "To: $sendToAddress\n"; print MAIL "From:$myEmailAddress\n"; print MAIL "Subject: $subject\n"; print MAIL "This is themessage body.\n"; print MAIL "Put your message here in the body.\n"; close (MAIL);60. How to read from a pipeline with Perl?Ans. To run the date command from a Perl program, and read the output of the command,all you need are a few lines of code like this: open(DATE, "date|"); $theDate = ;close(DATE); The open() function runs the external date command, then opens a filehandle DATE to the output of the date command. Next, the output of the date command isread into the variable $theDate through the file handle DATE. Example 2: The followingcode runs the "ps -f" command, and reads the output: open(PS_F, "ps -f|"); while (){ ($uid,$pid,$ppid,$restOfLine) = split; # do whatever I want with the variables here ... }close(PS_F);61. Why is it hard to call this function: sub y { "because" }Ans. Because y is a kind of quoting operator. The y/// operator is the sed-savvy synonymfor tr///. That means y(3) would be like tr(), which would be looking for a second string,as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][A-Z].62. What does `$result = f() .. g()' really return?Ans. False so long as f() returns false, after which it returns true until g() returns true, andthen starts the cycle again. This is scalar not list context, so we have the bistable flip-floprange operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()'. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignoredwhile g() later when g() is evaluated. Double dot is the inclusive range operator, f() andg() will both be evaluated on the same record. If you don't want that to happen, theexclusive range operator, triple dots, can be used instead. For extra credit, describe this:$bingo = ( a() .. b() ) ... ( c() .. d() );

Page 19: Unix Scripting&Perl

63. Why does Perl not have overloaded functions?Ans. Because you can inspect the argument count, return context, and object types all byyourself. 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 likeC++ where you can't do this, you simply must resort to overloading of functions.64. What does read() return at end of file?Ans. 0 A defined (but false) 0 value is the proper indication of the end of file for read()and sysread().65. What does `new $cur->{LINK}' do? (Assume the current package has no new()function of its own.)Ans. $cur->new()->{LINK} The indirect object syntax only has a single tokenlookahead. That means if new() is a method, it only grabs the very next token, not theentire following expression. This is why `new $obj[23] arg' does't work, as well as why`print $fh[23] "stuff\n"' does't work. Mixing notations between the OO and IO notationsis perilous. If you always use arrow syntax for method calls, and nothing else, you'll not be surprised.66. How do I sort a hash by the hash value?Ans. Here's a program that prints the contents of the grades hash, sorted numerically bythe hash value: #!/usr/bin/perl -w # Help sort a hash by the hash 'value', not the 'key'. tohighest). sub hashValueAscendingNum { $grades{$a} <=> $grades{$b}; } # Help sort ahash by the hash 'value', not the 'key'. # Values are returned in descending numeric order # (highest to lowest). sub hashValueDescendingNum { $grades{$b} <=> $grades{$a}; }%grades = ( student1 => 90, student2 => 75, student3 => 96, student4 => 55, student5 =>76, ); print "\n\tGRADES IN ASCENDING NUMERIC ORDER:\n"; foreach $key (sorthashValueAscendingNum (keys(%grades))) { print "\t\t$grades{$key} \t\t $key\n"; } print "\n\tGRADES IN DESCENDING NUMERIC ORDER:\n"; foreach $key (sorthashValueDescendingNum (keys(%grades))) { print "\t\t$grades{$key} \t\t $key\n"; }67. How to read file into hash array ?Ans. open(IN, ") { chomp; $hash_table{$_} = 0; } close IN; print "$_ =$hash_table{$_}\n" foreach keys %hash_table;68. how do find the length of an array?Ans. $@array69, What value is returned by a lone `return;' statement?Ans. 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 withoutworrying about the context in which they were called.70. What's the difference between /^Foo/s and /^Foo/?Ans. The second would match Foo other than at the start of the record if $* were set. Thedeprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, yousuppress any settings of that spooky variable, and force your carets and dollars to matchonly at the ends of the string and not at ends of line as well -- just as they would if $*weren't set at all.71. Does Perl have reference type?Ans. Yes. Perl can make a scalar or hash type reference by using backslash operator. For example $str = "here we go"; # a scalar variable $strref = \$str; # a reference to a scalar @array = (1..10); # an array $arrayref = \@array; # a reference to an array Note that thereference itself is a scalar.72. How to dereference a reference?Ans. There are a number of ways to dereference a reference. Using two dollar signs todereference a scalar. $original = $$strref; Using @ sign to dereference an array. @list =@$arrayref; Similar for hashes.

 73. What does length(%HASH) produce if you have thirty-seven random keys in a newlycreated hash?Ans.5 length() is a built-in prototyped as sub length($), and a scalar prototype

Page 20: Unix Scripting&Perl

silentlychanges aggregates into radically different forms. The scalar sense of a hash is false (0) if it's empty, otherwise it's a string representing the fullness of the buckets, like "18/32" or "39/64". The length of that string is likely to be 5. Likewise, `length(@a)' would be 2 if there were 37 elements in @a.74. If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR}and *{"Foo::".EXPR}?Ans. The second is disallowed under `use strict "refs"'. Dereferencing a string with*{"STR"} is disallowed under the refs stricture, although *{STR} would not be. This issimilar in spirit to the way ${"STR"} is always the symbol table variable, while ${STR}may be the lexical variable. If it's not a bareword, you're playing with the symbol table ina particular dynamic fashion.75. How do I do < fill-in-the-blank > for each element in an array?Ans. #!/usr/bin/perl -w @homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth'); foreach(@homeRunHitters) { print "$_ hit a lot of home runs in one year\n"; }76. How do I replace every character in a file with a comma?Ans. perl -pi.bak -e 's/\t/,/g' myfile.txt77. What is the easiest way to download the contents of a URL with Perl?Ans. 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/';78. how to concatinate strings in Perl?Ans. through . Operator.79. How do I read command-line arguments with Perl?Ans. 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-linearguments.\n"; foreach $argnum (0 .. $#ARGV) { print "$ARGV[$argnum]\n"; }80. When would `local $_' in a function ruin your day?Ans. When your caller was in the middle for a while(m//g) loop The /g state on a globalvariable is not protected by running local on it. That'll teach you to stop using locals. Too bad $_ can't be the target of a my() -- yet.81. What happens to objects lost in "unreachable" memory..... ?Ans. What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }' ? Their destructors are calledwhen that interpreter thread shuts down. When the interpreter exits, it first does anexhaustive search looking for anything that it allocated. This allows Perl to be used inembedded and multithreaded applications safely, and furthermore guarantees correctnessof object code.82. Assume that $ref refers to a scalar, an array, a hash or to some nested data structure.Explain the following statements:Ans. $$ref; # returns a scalar $$ref[0]; # returns the first element of that array $ref- > [0];# returns the first element of that array @$ref; # returns the contents of that array, or number of elements, in scalar context $&$ref; # returns the last index in that array $ref- >[0][5]; # returns the sixth element in the first row @{$ref- > {key}} # returns thecontents of the array that is the value of the key "key"83. How do you match one letter in the current locale?Ans. /[^\W_\d]/ We don't have full POSIX regexps, so you can't get at the isalpha() macrosave indirectly. You ask for one byte which is neither a non-alphanumunder, nor an under,nor a numeric. That leaves just the alphas, which is what you want.

Page 21: Unix Scripting&Perl

84. How do I print the entire contents of an array with Perl? Ans. To answer this question, we first need a sample array. Let's assume that you have anarray that contains the name of baseball teams, like this: @teams = ('cubs', 'reds','yankees', 'dodgers'); If you just want to print the array with the array members separated by blank spaces, you can just print the array like this: @teams = ('cubs', 'reds', 'yankees','dodgers'); print "@teams\n"; But that's not usually the case. More often, you want eachelement printed on a separate line. To achieve this, you can use this code: @teams =('cubs', 'reds', 'yankees', 'dodgers'); foreach (@teams) { print "$_\n"; }84. Perl uses single or double quotes to surround a zero or more characters. Are thesingle(' ') or double quotes (" ") identical?Ans. They are not identical. There are several differences between using single quotesand double quotes for strings. 1. The double-quoted string will perform variableinterpolation on its contents. That is, any variable references inside the quotes will bereplaced by the actual values. 2. The single-quoted string will print just like it is. Itdoesn't care the dollar signs. 3. The double-quoted string can contain the escapecharacters like newline, tab, carraige return, etc. 4. The single-quoted string can containthe escape sequences, like single quote, backward slash, etc.85. 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 astring like double-quoted string/ qq^this is a string like double-quoted string^ q/this is astring/ q&this is a string& q(this is a string)86. 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 aretruly private, and they will persist even when their block exits if something still caresabout them. Thus: { my $i = 0; sub next_i { $i++ } sub last_i { --$i } } creates twofunctions 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.87. Explain the difference between the following in Perl: $array[3] vs. $array->[3]Ans. because Perl's basic data structure is all flat, references are the only way to buildcomplex structures, which means references can be used in very tricky ways. Thisquestion is easy, though. In $array[3], "array" is the (symbolic) name of an array (@array) and $array[3] refers to the 4th element of this named array. In $array->[3],"array" is a hard reference to a (possibly anonymous) array, i.e., $array is the reference tothis array, so $array->[3] is the 4th element of this array being referenced.88, how to remove duplicates from an array?Ans. There is one simple and elegant solution for removing duplicates from a list inPERL @array = (2,4,3,3,4,6,2); my %seen = (); my @unique = grep { ! $seen{ $_ }++ }@array; print "@unique";


Top Related