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 know

2. 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. the included 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 include objects 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 only removes what is currently defined as the $INPUT_RECORD_SEPARATOR. whenever you call 'chomp ', it checks the value of a special variable '$/'. whatever the value of '$/' is eliminated 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 like file1-> 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 there
if (! -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' filename -----------------------------------------------------------------------

9. 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?
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 a LIST of values and converts it into a string. The string contaings a con-catenation of the converted values. Typically, each converted values looks like its machine-level repesentation. 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 and shift() 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 at that time eg. 1-10bytes, 2-18bytes.. you 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 will know the size 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 called within that block, but one defined as 'local' canlive within the block and have its visibility in 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 an XML::DOM node tree and use the getnodevalue to recover the data. DOM Parser is used when it is neede to do node operation. Instead we may use SAX parser if you require simple processing of the xml structure. -------------------------------------------------------------------------------------------------------

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 like deleting 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 show less warning) ------------------------------------------------------------------------------------------------------------

18. what is it meants by '$_'?
Ans. it is a default variable which holds automatically, a list of arguements passed to the subroutine within parentheses. -------------------------------------------------------------------------------------------------------------

19. How to connect to sql server through Perl?
Ans. We use the DBI(Database Independent Interface) module to connect to any database. 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 keeping track 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 interface ----------------------------------------------------------------------------------------

24. what is your favorite module in Perl?
Ans. CGI and DBI. CGI(Common Gateway Interface) because we do not need to worry about 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, with individual elements selected by some index value which essentially are scallars and called 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 have long list of words that are nto quoted or youjust do not want to type those quotes as youtype 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 an extended advantages of having enormous library. 2. you do not need to write everything from 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 system forks 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 thousands of Perl Modules, source and documentation, and all under GNU/GPL or smilar licence. you can go to www.cpan.org for more details. Some linux distribution provide a till names '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 a subroutine, 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 the sql statement in a hash format. -------------------------------------------------------------------------------------------------

35. what is the difference between C and Perl?
Ans. make up --------------------------------------------------------------------------------------------------

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

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 environment variables. Because %ENV is a hash, you can set environment variables just as you'd set the value of any Perl hash variable. Here's how you can set your PATH variable to make sure the following four directories are in your path:: $ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/home/yourname/bin'; --------------------------------------------------------------------------------------------------------------

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't support 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 foreign objects. 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 read from. 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 read access: open (CHECKBOOK, "checkbook.txt"); In this example, the name "CHECKBOOK" is the file handle that you'll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named "CHECKBOOK". Now that we've opened the checkbook file, we'd like 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 $record contains the contents of the first line of the checkbook file. The "<>" symbol is called the line 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); ------------------------------------------------------------------------------------------------------------------------

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 directory
Ans. 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 Perl statement. One-liner may contain many statements in one line. --from a script file, called Perl 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. Note that 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(), are variously 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 free things before you're done using them -----------------------------------------------------------------------------------------------------------

49. 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 in concept and the numbers and strings are exchangeable. Scalar variable is a Perl variable that is used to store scalar data. It uses a dollar sign $ and followed by one or more aphanumeric characters or underscores. It is case sensitive. --------------------------------------------------------------------------------------------------------------

50. Assuming $_ contains HTML, which of the following substitutions will remove all tags 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. It takes 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.cpp -----------------------------------------------------------------------------------------------------------

53. 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 extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the 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 point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it. -------------------------------------------------------------------------------------------------------------

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 (sort keys %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 student name: #!/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 jane 79 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 and the 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 go through a quick example here.Assuming that you've already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and 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 the message 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 file handle DATE to the output of the date command. Next, the output of the date command is read into the variable $theDate through the file handle DATE. Example 2: The following code 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 synonym for 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, and then starts the cycle again. This is scalar not list context, so we have the bistable flip-flop range 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 ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will both be evaluated on the same record. If you don't want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this: $bingo = ( a() .. b() ) ... ( c() .. d() ); ---------------------------------------------------------------------

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

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 token lookahead. That means if new() is a method, it only grabs the very next token, not the entire 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 notations is 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 by the hash value: #!/usr/bin/perl -w # Help sort a hash by the hash 'value', not the 'key'. to highest). sub hashValueAscendingNum { $grades{$a} <=> $grades{$b}; } # Help sort a hash 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 (sort hashValueAscendingNum (keys(%grades))) { print "\t\t$grades{$key} \t\t $key\n"; } print "\n\tGRADES IN DESCENDING NUMERIC ORDER:\n"; foreach $key (sort hashValueDescendingNum (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. $@array ------------------------------------------------------------------------------------------------------------

69, 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 without worrying 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. The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only 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 the reference 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 to dereference 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 newly created hash?
Ans.5 length() is a built-in prototyped as sub length($), and a scalar prototype silently changes 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 is similar 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 in a 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.txt --------------------------------------------------------------------------------------------------------

77. 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-line arguments.\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 global variable 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 called when that interpreter thread shuts down. When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code. -------------------------------------------------------------------------------------------------------------------------

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 the contents 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() macro save 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. -------------------------------------------------------------------------------------------------------------

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 an array 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 each element 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 the single(' ') or double quotes (" ") identical?
Ans. They are not identical. There are several differences between using single quotes and double quotes for strings. 1. The double-quoted string will perform variable interpolation on its contents. That is, any variable references inside the quotes will be replaced by the actual values. 2. The single-quoted string will print just like it is. It doesn't care the dollar signs. 3. The double-quoted string can contain the escape characters like newline, tab, carraige return, etc. 4. The single-quoted string can contain the escape sequences, like single quote, backward slash, etc. ----------------------------------------------------------------------------------------------------------------------

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 a string like double-quoted string/ qq^this is a string like double-quoted string^ q/this is a string/ q&this is a string& q(this is a string) ------------------------------------------------------------------------------------------------------------

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 are truly private, and they will persist even when their block exits if something still cares about them. Thus: { my $i = 0; sub next_i { $i++ } sub last_i { --$i } } creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it. --------------------------------------------------------------------------------------------------------------

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 build complex structures, which means references can be used in very tricky ways. This question 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 to this 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 in PERL @array = (2,4,3,3,4,6,2); my %seen = (); my @unique = grep { ! $seen{ $_ }++ } @array; print "@unique";