Friday, June 10, 2011

Crack the Perl Interview: 80+ Essential Questions and Answers

1. What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?
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.

2. If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{"Foo::".EXPR}?
The second is disallowed under use strict "refs". Dereferencing a string with *{"STR"} is disallowed under the refs stricture, although *{STR} would not be. If it's not a bareword, you're playing with the symbol table in a particular dynamic fashion.

3. How do I do <fill-in-the-blank> for each element in an array?

Perl
#!/usr/bin/perl -w
@homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth');
foreach (@homeRunHitters) {
    print "$_ hit a lot of home runs in one year\n";
}

4. How do I replace every <TAB> character in a file with a comma?
perl -pi.bak -e 's/\t/,/g' myfile.txt

5. What is the easiest way to download the contents of a URL with Perl?
Once you have the libwww-perl library and LWP.pm installed:

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

6. How to concatenate strings with Perl?

  • Method 1 (Dot operator): $filename = "/tmp/" . $name . ".tmp";

  • Method 2 (Join function): $filename = join "", "/tmp/", $name, ".tmp";

  • Method 3 (Variable interpolation): $filename = "/tmp/${name}.tmp";

7. How do I read command-line arguments with Perl?
Command-line arguments are stored in the @ARGV array. $#ARGV is the subscript of the last element, so the total number of arguments is $#ARGV + 1.

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

8. When would local $_ in a function ruin your day?
When your caller is in the middle of a while(m//g) loop. The /g state on a global variable is not protected by running local on it.

9. What happens to objects lost in "unreachable" memory?
Their destructors are called when that interpreter thread shuts down. When the interpreter exits, it does an exhaustive search for anything it allocated, guaranteeing the correctness of object code.

10. Explain the following statements when $ref refers to a nested data structure:

  • $$ref; — Returns a scalar.

  • $$ref[0]; or $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.

11. How do you match one letter in the current locale?
/[^\W_\d]/. You ask for one byte which is neither a non-alphanumeric, nor an underscore, nor a numeric, leaving just the alphas.

12. Are single (' ') or double quotes (" ") identical?
No. Double quotes perform variable interpolation and accept escape sequences (like \n). Single quotes print exact literal strings and ignore variable dollar signs.

13. How many ways can we express a string in Perl?
Many. For example: "string", qq/string/, qq^string^, q/string/, q&string&, and q(string).

14. How do you give functions private variables that retain their values between calls?
Create a scope surrounding that subroutine that contains lexicals (closures).

Perl
{ 
    my $i = 0; 
    sub next_i { $i++ } 
    sub last_i { --$i } 
}

15. What is meant by die in a Perl program?
It means to stop proceeding with the rest of the script if a previously defined condition is not met.

16. What is the use of require?
It is a call to an external program/condition that has to be met before the script can continue execution.

17. What does $^0 mean?
It holds the name of the default heading format for the default file handle (usually the file handle’s name with _TOP appended to it).

18. What is meant by chomp?
chomp is used to safely eliminate the trailing newline or carriage return character from a string.

19. What is meant by a pack in Perl?
It takes an array or list of values and packs it into a binary structure, returning the string containing that structure.

20. What does the -> symbol mean?
It is an infix dereference operator. It is used to dereference array subscripts, hash keys, or subroutines, and is also used for method invocation (e.g., invocant->method).

21. What are the benefits of having global and local variables?
Global variables can be called upon anywhere in the script. Local variables are securely contained and are not valid outside the specific code blocks where they are created.

22. What is a subroutine?
A subroutine is a named block of code (like a function) called upon to execute a specific task.

23. What does the word &myvariable mean and what is the purpose of the & symbol?
The & symbol is used to identify and call a sub-routine (&myvariable calls that specific subroutine).

24. What does $_ mean?
It is the default, general-purpose variable in Perl.

25. What interface is used in Perl to connect to a database?
The Database Independent Interface (DBI) module. Example: my $dbh = DBI->connect('dbi:Oracle:orcl', 'username', 'password');

26. When do you not use Perl for a project?
It is generally less suited for heavily structured web-based GUI applications, projects where shell scripts grow into massive enterprise libraries without planning, or strictly backend heavy data extraction/transformation without text manipulation.

27. Name an instance you used a CPAN module.
Common examples are CGI for web scripts and DBI for database connectivity.

28. Difference between for & foreach, and exec & system?
There is no difference between for and foreach. exec switches to the given process and never returns to the Perl script. system forks off the process, waits for it to complete, and then returns.

29. What’s the purpose of -w, strict, and -T?
-w enables warning messages. use strict forces you to declare variables before using them (preventing typos).

30. How to connect with SqlServer from Perl and display table info?
Use the DBI module alongside a database-specific driver. For SQL Server, this could be mssql::oleDB or Win32::ODBC. The interface code remains standard across databases thanks to DBI.

31. What’s the significance of @ISA, @EXPORT, @EXPORT_OK, and %EXPORT_TAGS in a Perl package?
@ISA keeps track of classes the package is inheriting. @EXPORT stores subroutines to be exported automatically. @EXPORT_OK stores subroutines exported only upon specific request.

32. What is the difference between use and require?

  • Use: Only for modules (.pm), verified at compile time, no file extension needed.

  • Require: Used for libraries and modules, verified at run time, requires the file extension.

33. What is the difference between my and local variable scope declarations?
Variables declared with my() are strictly visible only within the block that names them. local() variables are dynamically scoped; they are visible to the block and to any routines called from within that block.

34. What is a static function?
A function whose scope is strictly limited to the current source file (local scope), preventing visibility to outside or external source files.

35. How do I find which modules are installed on my system?

  • Use ExtUtils::Installed.

  • Search .pm files using File::Find::Rule.

  • Check documentation from the terminal using perldoc Module::Name.

  • Run a quick one-liner: perl -MModule::Name -e1.

36. How can I compare two dates and find the difference?
Store dates as epoch numbers and subtract them, or utilize CPAN modules like Date::Manip, Date::Calc, or DateTime for formatted dates.

37. How do I remove consecutive pairs of characters?
Use substitution s/(.)\1/$1/g; or the transliteration operator tr///cs;.

38. How can I access or change N characters of a string?
Use the substr() function: substr( $string, 0, 1 );. It can also be used as an lvalue to replace characters: substr( $string, 13, 4 ) = "Perl 5.8.0";.

39. How do I change the Nth occurrence of something?
Keep a running count inside a substitution evaluation block:

Perl
$count = 0;
s{((whom?)ever)}{ ++$count == 5 ? "${2}soever" : $1 }ige;

40. How can I count the number of occurrences of a substring within a string?
For single characters, use tr/X//. For multi-character substrings, use a while loop with a global match (while ($string =~ /-\d+/g) { $count++ }), or assign a global match to a scalar: $count = () = $string =~ /-\d+/g;.

41. How do I capitalize all the words on one line?
$line =~ s/\b(\w)/\U$1/g;

42. What is the difference between a list and an array?
An array is a variable with a changeable length that can be manipulated (push/pop). A list is a static set of values.

43. Why does defined() return true on empty arrays and hashes?
Because defined() is designed to be used on scalars or functions, not on aggregates like arrays and hashes.

44. How do I sort a hash (optionally by value instead of key)?
Sort by keys: my @keys = sort { $a cmp $b } keys %hash;
Sort by values: my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;

45. How can I make my hash remember the order I put elements into it?
Use the Tie::IxHash module from CPAN.

46. What's the difference between "delete" and "undef" with hashes?
undef $hash{'a'} changes the value of the key to undefined but leaves the key in the hash (it still exists). delete $hash{'a'} completely removes the key/value pair from the hash.

47. How do I send e-mail from a Perl/CGI program on a Unix system?
Open a pipeline directly to the Unix sendmail program:

Perl
open(MAIL, "|/usr/lib/sendmail -t");
print MAIL "To: $sendToAddress\n";
print MAIL "Subject: $subject\n";
close (MAIL);

48. How to read from a pipeline with Perl?
Open a process with a pipe:

Perl
open(DATE, "date|");
$theDate = <DATE>;
close(DATE);

49. Why is it hard to call this function: sub y { "because" }?
Because y/// is a built-in quoting operator (a synonym for tr///), which confuses the compiler.

50. What does $result = f() .. g() really return?
It acts as a bistable flip-flop range operator. It returns false until f() returns true, after which it returns true until g() returns true.

51. Why does Perl not have overloaded functions?
Because you can natively inspect the argument count (@_), return context (wantarray()), and object types (ref()) dynamically inside a single function, making C++ style overloading redundant.

52. What does read() return at end of file?
0. A defined but false value properly indicates EOF.

53. What does new $cur->{LINK} do?
Due to single-token lookahead in indirect object syntax, it evaluates as $cur->new()->{LINK}.

54. How to read a file into a hash array?

Perl
open(IN, "<name_file") or die "Couldn't open file: $!";
while (<IN>) {
   chomp;
   $hash_table{$_} = 0;
}
close IN;

55. How do you find the length of an array?
$@array (Note: standard practice is $#array + 1 or evaluating the array in a scalar context).

56. What value is returned by a lone return; statement?
The undefined value in scalar context, and the empty list value () in list context.

57. What's the difference between /^Foo/s and /^Foo/?
The /s modifier suppresses settings of the deprecated $* variable, forcing anchors to match only at the absolute ends of the string, not at internal newlines.

58. Does Perl have a reference type?
Yes. You can make a reference by using the backslash operator (e.g., $strref = \$str;).

59. How to dereference a reference?
Prepend the correct symbol type to the reference variable (e.g., $$strref for scalars, @$arrayref for arrays).

60. How do I generate a list of all .html files in a directory?

Perl
opendir(DIR, ".");
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);

61. What is a Perl one-liner?
A Perl script typed and executed immediately on the command line using the -e flag, without needing an external script file.

62. Assuming both a local($var) and a my($var) exist, what's the difference between ${var} and ${"var"}?
${var} evaluates the lexical (my) variable. ${"var"} performs a symbol table lookup and targets the dynamic (local) variable.

63. What happens when you return a reference to a private variable?
Perl’s garbage collector keeps track of variables and will not free the memory before you are completely done using it.

64. How to turn on Perl warnings and why is it important?
Use -w on the command line or #!/usr/bin/perl -w in the shebang. It exposes common mistakes, poor formatting, and syntax bugs, saving hours of debugging.

65. What are scalar data and scalar variables?
Scalar data represents a single item (a number or a string). A scalar variable stores this data, always begins with a $, and is case-sensitive.

66. Assuming $_ contains HTML, which substitutions will remove all tags in it?
Simple regex (s/<.*?>//gs) is fundamentally flawed due to HTML comments, bad formatting, and script tags. A real HTML parser is required.

67. How would if (isset($HTTP_POST_VARS)) from PHP look in Perl?
if ($ENV{'REQUEST_METHOD'} eq 'POST'){ ... }

68. What is the output of the following Perl program?
$p1 = "prog1.java"; $p1 =~ s/(.*)\.java/$1.cpp/; print "$p1\n";
Output: prog1.cpp

69. Why aren't Perl's patterns regular expressions?
Perl patterns support backreferences (like \1), meaning the state machine must remember old states. This disqualifies them as finite automatons (strict "regular expressions" in computer science).

70. What does Perl do if you try to exploit the execve(2) race involving setuid scripts?
It sends mail to root and exits.

71. How do I do <fill-in-the-blank> for each element in a hash?

Perl
foreach $key (sort keys %days) {
   print "The long name for $key is $days{$key}.\n";
}

72. How do you print out the next line from a filehandle with all its bytes reversed?
print scalar reverse scalar <FH> (Both reverse and <FH> must be explicitly put in scalar context).

73. Why do you use Perl?
It is a powerful, free interpreter that is highly portable, flexible, and heavily specialized for system administration and text manipulation.

74. How do I set environment variables in Perl programs?
Assign values directly to the special %ENV hash: $ENV{'PATH'} = '/bin:/usr/bin';.

75. Which of these is a difference between C++ and Perl?
Perl supports closures with unreachable private data acting as objects. C++ supports pointer arithmetic allowing you to alter memory access rights, which Perl avoids.

76. How to open and read data files with Perl?
Use the open() function to assign a file handle, then read it using the line reading operator <>:

Perl
open (CHECKBOOK, "checkbook.txt");
while ($record = <CHECKBOOK>) { print $record; }

77. How do I do fill_in_the_blank for each file in a directory?

Perl
opendir(DIR, ".");
@files = readdir(DIR);
foreach $file (@files) { print "$file\n"; }

78. What is Perl?
A high-level programming language with an eclectic heritage (C, sed, awk) known for excellent text manipulation, system management, database access, and quick prototyping.

79. What is the purpose of the first line #!/usr/bin/perl in a Perl Program?
It dictates the system path to the script interpreter, ensuring the shell (especially web servers running CGI) knows where to find the Perl executable to run the program.

No comments: