27
What is perl? perl is a programming language based off of C, shell, Lisp and a few other things. It is mostly used for OS program, network operations and some website development (mostly cgi). Write a script for 'count the no.of digits using regular expressions in perl.. #!/usr/bin/perl -w use strict; my($test,$number) = ("",""); $test = "12344tyyyyy456"; $number = ($test =~ tr/[0-9]/[0-9]/); print "Number of digits in variable is :- $number "; exit; What is the difference between chop & chomp functions in perl? chop is used remove last character,chomp function removes only line endings. What is Hash? Hash is an associative array where data is stored in "key"->"value" pairs. Eg : fruits is a hash having their names and price %fruits = ("Apple", "60", "Banana", "20", "Peers", "40"); When would you use Perl for a project? 1. When you are developing an application for a real time system in which processing speed is of utmost importance When to use Perl 1. For large text processing 2. When application does lot of data manipulation

Perl Interview

  • Upload
    asmanu

  • View
    7.889

  • Download
    1

Embed Size (px)

DESCRIPTION

Perl Interview questions and answers

Citation preview

Page 1: Perl Interview

What is perl?perl is a programming language based off of C, shell, Lisp and a few other things. It is mostly used for OS program, network operations and some website development (mostly cgi).

Write a script for 'count the no.of digits using regular expressions in perl..

#!/usr/bin/perl -w

use strict;my($test,$number) = ("","");$test = "12344tyyyyy456";$number = ($test =~ tr/[0-9]/[0-9]/);print "Number of digits in variable is :- $number "; exit;

What is the difference between chop & chomp functions in perl? chop is used remove last character,chomp function removesonly line endings.

What is Hash?Hash is an associative array where data is stored in "key"->"value" pairs.

Eg : fruits is a hash having their names and price%fruits = ("Apple", "60", "Banana", "20", "Peers", "40");

When would you use Perl for a project?

1. When you are developing an application for a real time system in which processing speed is of utmost importance

When to use Perl1. For large text processing2. When application does lot of data manipulation3. When you need fast development4. For database loading operations5. When shell scrits grow to become libraries

How would you replace a char in string and how do you store the number of replacements? $str='Hello';$cnt= ($str=~s/l/i/g);print $cnt;

Page 2: Perl Interview

How do you open a file for writing? open FILEHANDLE, ">$FILENAME"

Name an instance where you used a CPAN module? we will get a no.of modules from CPAN ,there so many module for database interface,database drivers.to do the mathematical operations ,text processing .each module is to handle a small tasks .

There are no.of instances for thisFor eg; we use DBI module for database connectivity,and we also use CGI Module for parsing the form input and printing the headers.

What is the difference between for & foreach, exec & system? Technically, there's no difference between for and foreach other than some style issues.

One is an alias of another. You can do things like thisforeach (my $i = 0; $i < 3; ++$i) { # normally this is foreach print $i, "n";}for my $i (0 .. 2) { # normally this is for print $i, "n";}

- exec runs the given process, switches to its name and never returns while system forks off the given process, waits for it to complete and then returns.

What purpose does each of the following serve: -w, strict, - T ? -w enables the warnings mode in perl

-T is enables the Taint mode it performs some checks howyour program is using the data passed to itTurn on strict mode to make Perl check for common mistakes.

Write a simple regular expression to match an IP address, e-mail address, city-state-zipcode

combination. /([0-255])(\.)$1\1$1\1$1/;

What?s your favorite module and why? My Favourite module is CGI.pm Bcoz it can handle almost all the tasks like1. parsing the form input2. printiing the headers

Page 3: Perl Interview

3. can handle cookies and sessionsand much more

Explain the difference between use and require? Use :1. The method is used only for the modules(only to include.pm type file)2. The included objects are varified at the time of compilation.3. No Need to give file extension.

Require:1. The method is used for both libraries and modules.2. The included objects are varified at the run time.3. Need to give file Extension.

Explain the difference between my and local? The variables declared with "my" can live only within the block it was defined and there is no visibility to inherited functions which were called within that block, but one defined with "local" they can live within the block and can have visibility in the functions which were called within that block.

What is -> Symbol in perl

reference the method of a module.

How do you check the return code of a command in Perl

system calls *traditionally* returns 0 when successful and 1 when it fails.system ( cmd ) && die "Error - could run cmdn";

 How to substitute a particular string in a file containing millions of records?perl -p -i.bak -e 's/search_str/replace_str/g'  filename...

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?bless $objref,'XYZ';

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

Takes a LIST of values and converts it into a string using the rules given by the TEMPLATE

How to implement stack in Perl?

Page 4: Perl Interview

Stack is LIFO (Last in First out), In perl that could be inplemented using the push() and shift() functions. push() adds the element at the last of array and shift() removes from the beginning of an array.

What is eval in perl?

 "eval" and "if ($@)" is the equivalent of a try/catch in the Cprogramming world. My question is how to basically throw an error inone perl script that can be caught by another

Consider the following example:

eval {

die("REASON"); # the script dies for some reason

};

if ($@) # $@ contains the exception that was thrown { print $@; }

What is Grep used for in Perl?You can able check the array contains a particular value is exist or not? For example see the below code.

@array = (1,2,3,4,5,6,7,8,100,200,500); # array$result = grep(/600/, @array); # checking the value.print $result; # the result will be 0. (if 1 then it contains the value)

I was asked how to implement the unix tail command in perl $ tail.pl t.txt 10 (display last 10 lines) I kind of managed with the simple ARRAY and they playing around with the $#Array etc but he wanted not without an array

you can use the following shell command in your perl script .

 `cat filename|tail -10f ;`

This may not be accepted as well. But this can be done in numerous ways ! One way is here :

maintain a structure which stores the line number and the size of the file at that time.eg 1 - 10bytes, 2 - 18 bytes ... you'll have to have a counter to increase the number of lines to find out the number of lines in the file. once you are through the file, you'll know the size of the file at any nth line. use sysseek to move the file pointer back to that position ( last 10 )and then start reading till the end.

why do you program in PERLPerl is easy, fast and its fun to code in perl.Perl is rich with various packages, N/w programming is very easy and there are lot more advantages to say.

How we can navigate the XML documents?You can use SAX if what you require is simple accesing of the xml structure. You can go for DOM if you need node handling capabilities like inserting a node, modifying a node, deleteing node and stuff like that.

Page 5: Perl Interview

How to remove a directory which has few files in it? I know about rmdir however it does not remove a dir which has files/dir in it!

rmtree($dir) ;  

What arguments do you frequently use for Perl Interpreter and what do they meanThe various command line arguments are -e executes the prog given as an argument-d start perl debugger on the file name specified as an argument-c compile the file given as an argumentThanks

-T for taint mode for security/input-checking -W for show all warnings mode (or -w to show less warnings)

what does this mean :'$_' ?It is a default variable which hold automatically the list of arguments passed to subroutines within parentheses.

What is @_ ?It is an array that contains all thedata that is passed to a function.

what are the characteristics of project that is well suited to PERL?actually it is used in automation testing....as a tester i am using per script for automation testing like running the tools etc.

How to Connect with SqlServer from perl and how to display database table info?In perl we have DBI module to connect to any database.step1: we need to intialise the DBI moduleuse DBI;step2 : connect to database using DBI module which reutrns database handle$dh = DBI->connect("dbi:mysql:database=DBname","username","password");step3 : to rertive data from database use select query $sth = $dh->prepare("select name,symbol from table");$sth->execute();while(@row = $sth->fetchrow_array()){print "name =$row[0],symbol = $row[1];}$dh->disconnect();

what's is the use of 'require' and what does this mean?require loads the code at run time. if the require file is not listed in the directory it produces an fatal error.

What is the difference between die and exit in perl?die: outputs stderr then exit and also it can trap errors by evalexit: just exits or exit with EXPR

Help in perl?

perldoc -f print

Page 6: Perl Interview

what is a Tk module? WHere it is used? What's the use of it? Plse tell me ..It provides a GUI

what does this mean '$^0'? tell briefly plse..Holds the name of the default heading format for the default file handle. Normally, it is equal to the file handle's name with _TOP appended to it.

what does 'qw(..)' mean? What's the use of it?when do we use it?the quoting opeator for lists is qw.advantage of qw is you need not quote the strings in additional way as qw already does quoting.

What is the difference between a perl program and a shell script? Which out of these is easier to understand and execute? And How?Whatever you want to write in shell script is possible in perl..the only diff is its easy to maintain and write perl scripts then shell.. lots of module etc are available for perl... u not need to rit everything frm scratch...also since earlier all the scripts are used to be written in shell now its required to maintain those thing.. no body want to touch it again which is working for years.. and its very tough too to port it in perl..

what is the use of "STDERR()"?STDERRThe special filehandle for standard error in any package.

What is difference between perl and jsp.What are the Advantagesif the code inside a page gets too big, or if you want to use it elsewhere, you can cut it out, make it into a Java class, and invoke it from anywhere in your application (even not from a page). With Perl, you're stuck inside the HTML box.Java programmers appreciate the importance of a clean language with complex OO data structures and strong typing.and we can also say ther are more ppl who are known to JAVA then Perl/PHP... and if u JAVA guy and getting same look and feel for Web (jsp) then why perl/PHP...above comment shows am against perl :) but am not.. perl is my fav. Language

What is CPAN ? What are the modules coming under this?CPAN ic Comprehencive Perl Archive Network. Its a repository contains thousands of Perl modules, source and documentation, and all under GNU/GPL or similar licence. you can go to www.cpan.org for more details. Some Linux distributions provide a tool named "cpan" with wich you can install packages directly from CPAN

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.

what's your experience of interfacing perl to database?DBI

advantages of C over perl?

In reality PERL interpreter is written in C. So what all advantages C have are also possesed by PERL. Otherwise C is faster than PERL, because PERL is an interpreted language.

Page 7: Perl Interview

perl regular expressions are greedy" what does this mean?Perl regular expressions normally match the longest string possible. that is what is called as "greedy match"

what does the word '&myvariable' mean?what does the symbol '&' means? What's purpose of it?

&myvariable is calling a sub-routine.

& is used to identify a sub-routine.

what is a subroutine?A subroutine is like a function ... called upon to excecute a task.

What is super?Super refers to current package ancestor.

What's the significance of @ISA, @EXPORT @EXPORT_OK %EXPORT_TAGS list & hashes in a perl package? With example?

@ISA ->  each package has its own @ISA array. this array keep track of classes it is inheriting.

ex:

package child;

@ISA=( parentclass);

@EXPORT this array stores the subroutins to be exported from a module.

@EXPORT_OK this array stores the subroutins to be exported only on request.

Given a table 'mailing':

CREATE TABLE mailing (addr VARCHAR(255) NOT NULL);

The mailing table will initially be empty. New addresses will be added on a daily basis. It is expected that the table will store at least 10,000,000 email addresses and 100,000 domains.

Write a perl script that updates another table which holds a daily count of email addresses by their domain name.

Page 8: Perl Interview

Use this table to report the top 50 domains by count sorted by percentage growth of the last 30 days compared to the total.

** NOTE **- You MUST use the provided DB.pm for all database interaction, and you must use it as it is (DB.pm cannot be modified except for the connection settings).

- The original mailing table should not be modified.

- All processing must be done in Perl (eg. no complex queries or sub-queries)

- Submit a compressed file(tar/zip) with the files required to run your script.--------------- DB.pm file contents are as follows

package GUI: B;

use strict;use DBI;

use vars qw(@ISA @EXPORT);use Exporter;@ISA = qw(Exporter);@EXPORT = qw(dbConnect query);

## dbConnect - connect to the database, get the database handle#sub dbConnect {

# Read database settings from config file:my $dsn = "DBI:mysql:database=test";my $dbh = DBI->connect( $dsn,'','',{ RaiseError => 1 } );

return $dbh;

}

## query - execute a query with parameters# query($dbh, $sql, @bindValues)#sub query {my $dbh = shift;my $sql = shift;my @bindValues = @_; # 0 or serveral parameters

my @returnData = ();

# issue querymy $sth = $dbh->prepare($sql);

if ( @bindValues ) {$sth->execute(@bindValues);} else {

Page 9: Perl Interview

$sth->execute();}

if ( $sql =~ m/^select/i ) {while ( my $row = $sth->fetchrow_hashref ) {push @returnData, $row;}}

# finish the sql statement$sth->finish();

return @returnData;}

__END__

i think the problem is straight forward and should be very simple to write a perl program for the same, below is the program. i havent run it to check if it works fine. comments are welcome

1. Assuming table 1 having the address has a structure

address_tbl (mailaddress char(255))

2. Assuming table 2 having the count of domains has a structure

domain_count_tbl (domain char(255), count int)

=========================================================================================

@maillist = query("select * from address_tbl")

for(i=0;i<scalar(@maillist;i++){ (name,domain) = split(/@/, myvar[i]) mylist[domain]++}

foreach $key (keys %mylist){ @res = query("select 1 from domain_count_tbl where domain=$key") if (scalar(@res) == 0 ) {  query(insert into domain_count_tbl values("$key",mylist[$key])) } else {  query(update domain_count_tbl set count=mylist[$key] where domain="$key") }}

Page 10: Perl Interview

Predefined Names

The following names have special meaning to perl. I could have used alphabetic symbols for some of these, but I didn't want to take the chance that someone would say reset "a-zA-Z" and wipe them all out. You'll just have to suffer along with these silly symbols. Most of them have reasonable mnemonics, or analogues in one of the shells. $_

The default input and pattern-searching space. The following pairs are equivalent: while (<>) {... # only equivalent in while!while ($_ = <>) {...

/^Subject:/$_ =~ /^Subject:/

y/a-z/A-Z/$_ =~ y/a-z/A-Z/

chopchop($_)

(Mnemonic: underline is understood in certain operations.) $.

The current input line number of the last filehandle that was read. Readonly. Remember that only an explicit close on the filehandle resets the line number. Since <> never does an explicit close, line numbers increase across ARGV files (but see examples under eof). (Mnemonic: many programs use . to mean the current line number.)

$/ The input record separator, newline by default. Works like awk's RS variable, including treating blank lines as delimiters if set to the null string. You may set it to a multicharacter string to match a multi-character delimiter. Note that setting it to "\n\n" means something slightly different than setting it to "", if the file contains consecutive blank lines. Setting it to "" will treat two or more consecutive blank lines as a single blank line. Setting it to "\n\n" will blindly assume that the next input character belongs to the next paragraph, even if it's a newline. (Mnemonic: / is used to delimit line boundaries when quoting poetry.)

$, The output field separator for the print operator. Ordinarily the print operator simply prints out the comma separated fields you specify. In order to get behavior more like awk, set this variable as you would set awk's OFS variable to specify what is printed between fields. (Mnemonic: what is printed when there is a , in your print statement.)

$"" This is like $, except that it applies to array values interpolated into a double-quoted string (or similar interpreted string). Default is a space. (Mnemonic: obvious, I think.)

Page 11: Perl Interview

$\ The output record separator for the print operator. Ordinarily the print operator simply prints out the comma separated fields you specify, with no trailing newline or record separator assumed. In order to get behavior more like awk, set this variable as you would set awk's ORS variable to specify what is printed at the end of the print. (Mnemonic: you set $\ instead of adding \n at the end of the print. Also, it's just like /, but it's what you get "back" from perl.)

$# The output format for printed numbers. This variable is a half-hearted attempt to emulate awk's OFMT variable. There are times, however, when awk and perl have differing notions of what is in fact numeric. Also, the initial value is %.20g rather than %.6g, so you need to set $# explicitly to get awk's value. (Mnemonic: # is the number sign.)

$% The current page number of the currently selected output channel. (Mnemonic: % is page number in nroff.)

$= The current page length (printable lines) of the currently selected output channel. Default is 60. (Mnemonic: = has horizontal lines.)

$- The number of lines left on the page of the currently selected output channel. (Mnemonic: lines_on_page - lines_printed.)

$~ The name of the current report format for the currently selected output channel. Default is name of the filehandle. (Mnemonic: brother to $^.)

$^ The name of the current top-of-page format for the currently selected output channel. Default is name of the filehandle with "_TOP" appended. (Mnemonic: points to top of page.)

$| If set to nonzero, forces a flush after every write or print on the currently selected output channel. Default is 0. Note that STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe, such as when you are running a perl script under rsh and want to see the output as it's happening. (Mnemonic: when you want your pipes to be piping hot.)

$$ The process number of the perl running this script. (Mnemonic: same as shells.)

$? The status returned by the last pipe close, backtick (\`\`) command or system operator. Note that this is the status word returned by the wait() system call, so the exit value of the subprocess is actually ($? >> 8). $? & 255 gives which signal, if any, the process died from, and whether there was a core dump. (Mnemonic: similar to sh and ksh.)

$&

Page 12: Perl Interview

The string matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval enclosed by the current BLOCK). (Mnemonic: like & in some editors.)

$\` The string preceding whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval enclosed by the current BLOCK). (Mnemonic: \` often precedes a quoted string.)

$' The string following whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval enclosed by the current BLOCK). (Mnemonic: ' often follows a quoted string.) Example: $_ = 'abcdefghi';/def/;print "$\`:$&:$'\n"; # prints abc:def:ghi

$+ The last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns matched. For example: /Version: (.*)|Revision: (.*)/ && ($rev = $+);

(Mnemonic: be positive and forward looking.) $*

Set to 1 to do multiline matching within a string, 0 to tell perl that it can assume that strings contain a single line, for the purpose of optimizing pattern matches. Pattern matches on strings containing multiple newlines can produce confusing results when $* is 0. Default is 0. (Mnemonic: * matches multiple things.) Note that this variable only influences the interpretation of ^ and $. A literal newline can be searched for even when $* == 0.

$0 Contains the name of the file containing the perl script being executed. Assigning to $0 modifies the argument area that the ps(1) program sees. (Mnemonic: same as sh and ksh.)

$<digit> Contains the subpattern from the corresponding set of parentheses in the last pattern matched, not counting patterns matched in nested blocks that have been exited already. (Mnemonic: like \digit.)

$[ The index of the first element in an array, and of the first character in a substring. Default is 0, but you could set it to 1 to make perl behave more like awk (or Fortran) when subscripting and when evaluating the index() and substr() functions. (Mnemonic: [ begins subscripts.)

$] The string printed out when you say "perl -v". It can be used to determine at the beginning of a script whether the perl interpreter executing the script is in the right range of versions. If used in a numeric context, returns the version + patchlevel / 1000. Example: # see if getc is available

($version,$patchlevel) = $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;

print STDERR "(No filename completion available.)\n"

Page 13: Perl Interview

if $version * 1000 + $patchlevel < 2016;

or, used numerically, warn "No checksumming!\n" if $] < 3.019;

(Mnemonic: Is this version of perl in the right bracket?) $;

The subscript separator for multi-dimensional array emulation. If you refer to an associative array element as $foo{$a,$b,$c}

it really means $foo{join($;, $a, $b, $c)}

But don't put @foo{$a,$b,$c} # a slice--note the @

which means ($foo{$a},$foo{$b},$foo{$c})

Default is "\034", the same as SUBSEP in awk. Note that if your keys contain binary data there might not be any safe value for $;. (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon. Yeah, I know, it's pretty lame, but $, is already taken for something more important.)

$! If used in a numeric context, yields the current value of errno, with all the usual caveats. (This means that you shouldn't depend on the value of $! to be anything in particular unless you've gotten a specific error return indicating a system error.) If used in a string context, yields the corresponding system error string. You can assign to $! in order to set errno if, for instance, you want $! to return the string for error n, or you want to set the exit value for the die operator. (Mnemonic: What just went bang?)

$@ The perl syntax error message from the last eval command. If null, the last eval parsed and executed correctly (although the operations you invoked may have failed in the normal fashion). (Mnemonic: Where was the syntax error "at"?)

$< The real uid of this process. (Mnemonic: it's the uid you came FROM, if you're running setuid.)

$> The effective uid of this process. Example: $< = $>; # set real uid to the effective uid($<,$>) = ($>,$<); # swap real and effective uid

(Mnemonic: it's the uid you went TO, if you're running setuid.) Note: $< and $> can only be swapped on machines supporting setreuid().

$( The real gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by getgid(), and the subsequent ones by getgroups(), one of which may be the same as the first number. (Mnemonic: parentheses are used to GROUP things. The real gid is the group you LEFT, if you're running setgid.)

$)

Page 14: Perl Interview

The effective gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by getegid(), and the subsequent ones by getgroups(), one of which may be the same as the first number. (Mnemonic: parentheses are used to GROUP things. The effective gid is the group that's RIGHT for you, if you're running setgid.)

Note: $<, $>, $( and $) can only be set on machines that support the corresponding set[re][ug]id() routine. $( and $) can only be swapped on machines supporting setregid().

$: The current set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format. Default is "\ \n-", to break on whitespace or hyphens. (Mnemonic: a "colon" in poetry is a part of a line.)

$^D The current value of the debugging flags. (Mnemonic: value of -D switch.)

$^F The maximum system file descriptor, ordinarily 2. System file descriptors are passed to subprocesses, while higher file descriptors are not. During an open, system file descriptors are preserved even if the open fails. Ordinary file descriptors are closed before the open is attempted.

$^I The current value of the inplace-edit extension. Use undef to disable inplace editing. (Mnemonic: value of -i switch.)

$^L What formats output to perform a formfeed. Default is \f.

$^P The internal flag that the debugger clears so that it doesn't debug itself. You could conceivable disable debugging yourself by clearing it.

$^T The time at which the script began running, in seconds since the epoch. The values returned by the -M , -A and -C filetests are based on this value.

$^W The current value of the warning switch. (Mnemonic: related to the -w switch.)

$^X The name that Perl itself was executed as, from argv[0].

$ARGV contains the name of the current file when reading from <>.

@ARGV The array ARGV contains the command line arguments intended for the script. Note that $#ARGV is the generally number of arguments minus one, since $ARGV[0] is the first argument, NOT the command name. See $0 for the command name.

@INC The array INC contains the list of places to look for perl scripts to be evaluated by the "do EXPR" command or the "require" command. It initially consists of the

Page 15: Perl Interview

arguments to any -I command line switches, followed by the default perl library, probably "/usr/local/lib/perl", followed by ".", to represent the current directory.

%INC The associative array INC contains entries for each filename that has been included via "do" or "require". The key is the filename you specified, and the value is the location of the file actually found. The "require" command uses this array to determine whether a given file has already been included.

$ENV{expr} The associative array ENV contains your current environment. Setting a value in ENV changes the environment for child processes.

$SIG{expr} The associative array SIG is used to set signal handlers for various signals. Example: sub handler { # 1st argument is signal name

local($sig) = @_;print "Caught a SIG$sig--shutting down\n";close(LOG);exit(0);

}

$SIG{'INT'} = 'handler';$SIG{'QUIT'} = 'handler';...$SIG{'INT'} = 'DEFAULT'; # restore default action$SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT

The SIG array only contains values for the signals actually set within the perl script.

1. List the files in current directory sorted by size ? - ls -l | grep ^- | sort -nr 2. List the hidden files in current directory ? - ls -a1 | grep "^\." 3. Delete blank lines in a file ? - cat sample.txt | grep -v ‘^$’ > new_sample.txt 4. Search for a sample string in particular files ? - grep “Debug” *.confHere grep

uses the string “Debug” to search in all files with extension“.conf” under current directory.

5. Display the last newly appending lines of a file during appendingdata to the same file by some processes ? - tail –f Debug.logHere tail shows the newly appended data into Debug.log by some processes/user.

6. Display the Disk Usage of file sizes under each directory in currentDirectory ? - du -k * | sort –nr (or) du –k . | sort -nr

Page 16: Perl Interview

7. Change to a directory, which is having very long name ? - cd CDMA_3X_GEN*Here original directory name is – “CDMA_3X_GENERATION_DATA”.

8. Display the all files recursively with path under current directory ? - find . -depth -print

9. Set the Display automatically for the current new user ? - export DISPLAY=`eval ‘who am i | cut -d"(" -f2 | cut -d")" -f1′`Here in above command, see single quote, double quote, grave ascent is used. Observe carefully.

10. Display the processes, which are running under yourusername ? - ps –aef | grep MaheshvjHere, Maheshvj is the username.

11. List some Hot Keys for bash shell ? - Ctrl+l – Clears the Screen. Ctrl+r – Does a search in previously given commands in shell. Ctrl+u - Clears the typing before the hotkey. Ctrl+a – Places cursor at the beginning of the command at shell. Ctrl+e – Places cursor at the end of the command at shell. Ctrl+d – Kills the shell. Ctrl+z – Places the currently running process into background.

12.  Display the files in the directory by file size ? - ls –ltr | sort –nr –k 5 13. How to save man pages to a file ? - man <command> | col –b > <output-

file>Example : man top | col –b > top_help.txt 14. How to know the date & time for – when script is executed ? - Add the

following script line in shell script.eval echo "Script is executed at `date`" >> timeinfo.infHere, “timeinfo.inf” contains date & time details ie., when script is executed and history related to execution.

15. How do you find out drive statistics ? - iostat -E 16. Display disk usage in Kilobytes ? - du -k 17. Display top ten largest files/directories ? - du -sk * | sort -nr | head 18. How much space is used for users in kilobytes ? - quot -af 19. How to create null file ? - cat /dev/null > filename1 20. Access common commands quicker ? - ps -ef | grep -i $@ 21. Display the page size of memory ? - pagesize -a 22. Display Ethernet Address arp table ? - arp -a 23. Display the no.of active established connections to localhost ? - netstat -a | grep

EST 24. Display the state of interfaces used for TCP/IP traffice ? - netstat -i 25. Display the parent/child tree of a process ? - ptree <pid> Example: ptree 1267 26. Show the working directory of a process ? - pwdx <pid> Example: pwdx 1267 27. Display the processes current open files ? - pfiles <pid> Example: pfiles 1267 28. Display the inter-process communication facility status ? - ipcs 29. Display the top most process utilizing most CPU ? - top –b 1 30. Alternative for top command ? - prstat -a 31. What does the pkgadd command do?

pkgadd is used to add a package to the solaris.It installs the package in the /usr/local directory by default.

What is RPC? Why do I need it?

Page 17: Perl Interview

RPC:A call to a procedure in a different address space. In a traditional procedure call, the calling procedure and the called procedure are in the same address space on one machine. In a remote procedure call, the calling procedure invokes a procedure in a different address space and usuallyon a different machine.

What does init 5 and init 0 do?

init 5 will shutdown and Power-off the server.

init 0 will bring the server to the ok> prompt (Fourth monitor)

What does ndd do?

ndd command will hardcore the speed of the network interface card.

What is OBP and how do you access it?

OBP is called as Open Boot PROM. This OBP can be accessiable thru ok> prompt (Fourth monitor)

How do you get system diagnostics information?

You can get system diagonostics information thru prtdiag command. And you can execute this command by

/usr/platform/’uname -m’/sbin/prtdiag -v|more

How do you boot from CD-ROM?

Booting form CD-ROM can be done by the commandok >boot cdrom

What is /etc/system for?

/etc/system is a kernal file of Solaris OS.

What does fmthard do?

fmthard will create partitions in a new disk as in a already created/designed disk.

Page 18: Perl Interview

For example we can get output from prtvtoc command and give as a input to the new disk as follows.

prtvtoc /dev/rmt/c0t0d0s0 > a | fmthard /dev/rmt/c1todos1

How do you boot from a Network with jumpstart?

boot net - install

How do you boot from CD-ROM?

boot cdrom

What is jumpstart?

The Jumpstart feature is an automatic installation process available in the Solaris operating environment. It allows system administrators to categorize machines on their network and automatically install systems based on the category to which a system belongs.

What is LOM

Short for LAN on motherboard. The term refers to a chip or chipset capable of network connections that has been embedded directly on the motherboard of a desktop, workstation or server. Instead of requiring a separate network interface card to access a local-area network, such as Ethernet, the circuits are attached to the motherboard. An advantage of a LOM system is an extra available PCI slot that is not being used by the network adapter.

What does fmthard do?

The fmthard command updates the VTOC (Volume Table of Contents) on hard disks and, on systems, adds boot information,to the Solaris fdisk partition. One or more of the options,-s datafile, -d data, or -n volume_name must be used to request modifications to the disk label. To print disk label contents, see prtvtoc.The /dev/rdsk/c?[t?]d?s2 file must be the character special file of the device where the new label is to be installed. On systems, fdisk must be run on the drive before fmthard.

How to create a package?

pkgmk -o -r / -d /tmp -f Prototype

How do you view shared memory statistics?

swap -l -> displays swap usage

Page 19: Perl Interview

prstat -> examines all active processes on the system and reports statistics based on the selected output mode and sort order

vmstat -> reports information about processes, memory, paging, block IO, traps, and cpu activity

pmap -> lists the virtual memory mappings underlying the given process

How do you get system diagnostics information?

prtdiag -v -> Shows mem, cpu, Power supply, add-on cards info, LEd statusiostat -En -> Shows disk status.(look for hard error)/var/adm/messages -> Logs most commont failures and the entire system events

Extended POST -> This can be done at boot time.

ipmitool -> Shows voltage, fanspee, led status etc…

What is VTS?

Sun Validation Test Suite -> tests and validates Sun hardware by verifying the configuration and functionality of hardware controllers, devices

What does ndd do?

allows you to tune, tweak, set and reset various parameters related to the TCP/IP stack while the system is running

1. Different Types of Joins-Inner JoinOuter Join - Right Outer JoinLeft Outer JoinCross Join

2. How will you copy the structure of a table without copying the data?

create table xyzas ( select * from abc where 1=0)

Page 20: Perl Interview

Diffrence between a “where” clause and a “having” clauseAnswers1.”where” is used to filter records returned by “Select”2.”where” appears before group by clause3.In “where” we cannot use aggrigate functions like where count(*)>2 etc4.”having” appears after group by clause5.”having” is used to filter records returned by “Group by”6.In”Having” we can use aggrigate functions like where count(*)>2 etcthere are two more

How to create a database link?A database link is an object in the local database that allows you to access objects on a remote database or to mount a secondary database in read-only mode.

CREATE [PUBLIC] DATABASE LINK dblink[CONNECT TO user IDENTIFIED BY password][USING ‘connect_string’]

What is the difference among “dropping a table”, “truncating a table” and “deleting all records” from a table.

Drop Table - will remove the existance of the table from the database along with its data and structure and all the constraints. The table will be no longer available.

Truncate Table - will remove all the rows (only the rows) from a table. it will not delete the table. Its a DDL statement that means the deleted rows cannot be reverted back by ROLLBACK statement;

Delete Table - is a DML statement which will delete rows from a table according to the matching criteria mentions in the ‘where’ clause. And these rows can be reverted back by ‘ROLLBACK’ statement if ‘COMMIT’ is not fired.