Core Perl Mechanics & Syntax
1. What does
length(%HASH) produce if you have thirty-seven random keys in a newly created hash?Answer: 5.
length() evaluates the scalar sense of the hash, which returns a string representing the fullness of the buckets (e.g., "18/32" or "39/64"). The length of that string is likely 5.2. If EXPR is an arbitrary expression, what is the difference between
$Foo::{EXPR} and *{"Foo::".EXPR}?Answer: The second is disallowed under
use strict "refs". Dereferencing a string with *{"STR"} is disallowed under the refs stricture, whereas playing with the symbol table directly is a dynamic fashion not blocked the same way.3. Are single (
' ') and double quotes (" ") identical in Perl?Answer: No. Double quotes perform variable interpolation and allow escape characters (like
\n). Single quotes print exact literal strings and do not interpolate variables.4. How many ways can we express a string in Perl?
Answer: Many ways, including:
" ", ' ', qq//, qq^ ^, q//, q& &, and q().5. What is meant by
die in a Perl program?Answer: It stops the script from proceeding if a previously defined condition is not met.
6. What is the use of
require and what does it do?Answer: It is a call to an external program or condition that must be met before the script can continue. Included objects are verified at run time, and it requires the file extension.
7. What does
$^0 mean?Answer: It holds the name of the default heading format for the default file handle (normally the file handle's name with
_TOP appended to it).8. What is meant by
chomp?Answer: It is used to eliminate the newline character or carriage return from the end of a string.
9. What is meant by
pack in Perl?Answer: It takes an array or list of values and packs it into a binary structure, returning the string containing that structure.
10. What does the
-> symbol mean?Answer: It is an infix dereference operator (for arrays, hashes, or subroutines) and is also used for method invocation (e.g.,
invocant->method).11. What does
$_ mean?Answer: It is the default variable in Perl.
12. What is the difference between a list and an array?
Answer: An array has a changeable length and can be manipulated (push/pop). A list is a static set of values.
13. What value is returned by a lone
return; statement?Answer: The undefined value in scalar context, and the empty list value
() in list context.14. Does Perl have a reference type?
Answer: Yes, created using a backslash (e.g.,
\$str for a scalar, \@array for an array).15. How do you dereference a reference?
Answer: Prefix the reference with the appropriate symbol type:
$$strref for a scalar, @$arrayref for an array.16. What happens when you return a reference to a private variable?
Answer: Perl keeps track of the variable (closure) and won't free the memory until you are completely done using it.
17. What are scalar data and scalar variables?
Answer: Scalar data represents a single item (a number or string). A scalar variable stores this data, starts with a
$, and is case-sensitive.Functions, Variables & Scope
18. What is the difference between
my and local variable scope declarations?Answer:
my() creates a lexical variable visible only within the specific block it is declared in. local() creates a dynamic variable that is also visible to any subroutines called from within that block.19. Assuming both a
local($var) and a my($var) exist, what's the difference between ${var} and ${"var"}?Answer:
${var} refers to the lexical (my) variable, while ${"var"} performs a symbol table lookup and refers to the dynamic (local) variable.20. When would
local $_ in a function ruin your day?Answer: When your caller is in the middle of a
while(m//g) loop, because the /g state on a global variable is not protected by local.21. How do you give functions private variables that retain their values between calls?
Answer: Create a lexical scope surrounding the subroutine. For example:
{ my $i = 0; sub next_i { $i++ } }.22. What are the benefits of having global and local variables?
Answer: Global variables can be called upon anywhere in the script. Local variables keep data contained and are not valid outside the code blocks where they are created.
23. What is a subroutine?
Answer: A block of code/function called upon to execute a specific task.
24. What does the word
&my variable mean and what is the purpose of the & symbol?Answer:
& is used to identify and call a subroutine.25. What’s the significance of
@ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS lists & hashes in a Perl package?Answer:
@ISA tracks inherited classes. @EXPORT stores subroutines to be exported automatically. @EXPORT_OK stores subroutines exported only on request.26. What is the difference between
use and require?Answer:
use includes modules (.pm), verifies at compile time, and doesn't need a file extension. require includes both libraries and modules, verifies at run time, and requires the file extension.27. What is a static function?
Answer: A function whose scope is limited strictly to the current source file (local scope).
28. Why is it hard to call this function:
sub y { "because" }?Answer: Because
y is a built-in quoting operator (a synonym for tr///), confusing the parser.29. What does
$result = f() .. g() really return?Answer: It acts as a bistable flip-flop: it returns false until
f() returns true, after which it returns true until g() returns true.30. Why does Perl not have overloaded functions?
Answer: Because Perl allows you to natively inspect the argument count (
@_), the return context (wantarray()), and the types of arguments (ref()), making C++ style overloading unnecessary.31. What does
new $cur->{LINK} do?Answer: Due to the single-token lookahead of indirect object syntax, it evaluates as
$cur->new()->{LINK} rather than evaluating the expression first.Hashes, Arrays & Data Manipulation
32. How do I do
<fill-in-the-blank> for each element in an array?Answer: Use a foreach loop:
foreach (@homeRunHitters) { print "$_\n"; }33. How do you find the length of an array?
Answer: Evaluate the array in a scalar context (e.g., assigning it to a scalar variable, or using
$#array + 1).34. Why does
defined() return true on empty arrays and hashes?Answer: You should only use
defined on scalars or functions, not on aggregates like arrays and hashes.35. How do I do
<fill-in-the-blank> for each element in a hash?Answer: Use
foreach with keys: foreach $key (sort keys %days) { print "$days{$key}\n"; }36. How do I sort a hash by the hash key?
Answer: Pass the keys to the sort function:
foreach $key (sort keys %hash) { ... }37. How do I sort a hash by the hash value?
Answer: Use a custom sort block to compare the values:
sort { $hash{$a} <=> $hash{$b} } keys %hash;38. How can I make my hash remember the order I put elements into it?
Answer: Use the
Tie::IxHash module from CPAN.39. What's the difference between
delete and undef with hashes?Answer:
undef $hash{'a'} leaves the key in the hash but changes its value to undefined. delete $hash{'a'} completely removes the key-value pair from the hash.40. Explain the following statements when
$ref refers to a nested data structure:Answer:
$$ref: returns a scalar$$ref[0]or$ref->[0]: returns the first element of that array@$ref: returns the array contents$&$ref: returns the last index in the array$ref->[0][5]: returns the sixth element in the first row
String Processing & Regular Expressions
41. How do you concatenate strings with Perl?
Answer: Using the dot operator (
.), the join function, or variable interpolation ("/tmp/${name}.tmp").42. How do you match one letter in the current locale?
Answer: Use
/[^\W_\d]/ (which looks for a byte that is not a non-alphanumeric, not an underscore, and not a number).43. How do I replace every
<TAB> character in a file with a comma?Answer: From the command line:
perl -pi.bak -e 's/\t/,/g' myfile.txt44. How do I remove consecutive pairs of characters?
Answer: Using substitution
s/(.)\1/$1/g; or transliteration tr///cs;.45. How can I access or change N characters of a string?
Answer: Use the
substr() function. For example: substr( $string, 0, 1 ) to get the first character.46. How do I change the Nth occurrence of something?
Answer: Maintain a counter variable inside the replacement block of a substitution loop, e.g.,
s{...}{ ++$count == 5 ? "swap" : $1 }ige;47. How can I count the number of occurrences of a substring within a string?
Answer: For single characters, use
tr/X//. For multi-character substrings, assign a global match to a scalar: $count = () = $string =~ /-\d+/g;48. How do I capitalize all the words on one line?
Answer: Use the uppercase escape sequence in a substitution:
$line =~ s/\b(\w)/\U$1/g;49. What's the difference between
/^Foo/s and /^Foo/?Answer: The
/s modifier suppresses settings of the deprecated $* variable, forcing anchors (^ and $) to match only at the true ends of the string.50. Assuming
$_ contains HTML, which substitutions will remove all tags in it?Answer: Simple regex (like
s/<.*?>//gs) is fundamentally flawed due to HTML comments, bad formatting, and <script> tags. A real parser is required.51. Why aren't Perl's patterns regular expressions?
Answer: Perl supports backreferences (e.g.,
\1). True regular expressions in computer science are finite automatons that do not require extra memory to track previous states.System, Files & Execution
52. How do I read command-line arguments with Perl?
Answer: They are stored in the
@ARGV array. The total number of arguments is $#ARGV + 1.53. What is the easiest way to download the contents of a URL with Perl?
Answer: Install
libwww-perl and use LWP::Simple: use LWP::Simple; $url = get 'http://www...';54. What interface is used in Perl to connect to a database?
Answer: The Database Independent Interface (
DBI) module.55. How to Connect with SqlServer from Perl?
Answer: Use the
DBI module alongside a database-specific driver like mssql::oleDB or Win32::ODBC.56. How do I send e-mail from a Perl/CGI program on a Unix system?
Answer: Open a pipeline to the server's sendmail program:
open(MAIL, "|/usr/lib/sendmail -t"); then print your headers and body to that filehandle.57. How to read from a pipeline with Perl?
Answer: Open a command with a pipe symbol at the end:
open(DATE, "date|"); $theDate = <DATE>; close(DATE);58. What does
read() return at end of file?Answer:
0. A defined but false value properly indicates EOF.59. How do I generate a list of all
.html files in a directory?Answer: Open the directory and use
grep: opendir(DIR, "."); @files = grep(/\.html$/,readdir(DIR)); closedir(DIR);60. What is a Perl one-liner?
Answer: Executing a Perl script directly from the command line using the
-e flag (e.g., perl -e "print 'Hello';") without needing a saved script file.61. How do you turn on Perl warnings and why is it important?
Answer: Use the
-w flag on the command line, in the shebang line #!/usr/bin/perl -w, or use warnings;. It is critical for catching common mistakes and saving debugging time.62. What does Perl do if you try to exploit the
execve(2) race involving setuid scripts?Answer: It sends an email to the root administrator and exits.
63. How do you print out the next line from a filehandle with all its bytes reversed?
Answer: Ensure both the reverse and filehandle are in scalar context:
print scalar reverse scalar <FH>64. How do I set environment variables in Perl programs?
Answer: Assign values directly to the special
%ENV hash (e.g., $ENV{'PATH'} = '/bin:/usr/bin';).65. How do you open and read data files with Perl?
Answer: Use the
open() function to assign a filehandle, then use the line reading operator < >: open(FH, "file.txt"); while ($record = <FH>) { print $record; }66. How do I do
<fill-in-the-blank> for each file in a directory?Answer:
opendir(DIR, "."); @files = readdir(DIR); foreach $file (@files) { ... }67. What is the purpose of the first line
#!/usr/bin/perl in a Perl Program?Answer: It acts as a shebang path for the shell to locate the correct script interpreter when executing the file, which is especially important for CGI programs that lack a standard path.
General Architecture & Use Cases
68. What happens to objects lost in "unreachable" memory?
Answer: Their destructors are triggered when the interpreter thread shuts down and does an exhaustive search for allocated items.
69. How do I find which modules are installed on my system?
Answer: You can use
ExtUtils::Installed, File::Find::Rule, or simply type perldoc Module::Name in the terminal to see if documentation exists.70. How can I compare two dates and find the difference?
Answer: Convert them to epoch time numbers and subtract, or use modules like
Date::Manip, Date::Calc, or DateTime.71. What is the difference between
for & foreach, and exec & system?Answer: There is no difference between
for and foreach. exec switches entirely to the requested process and never returns to the Perl script. system forks off the process, waits for it to complete, and then returns to the script.72. Name an instance you used a CPAN module.
Answer: Common answers involve utilizing
CGI for web scripts and DBI for database connectivity.73. When do you not use PERL for a project?
Answer: According to the text snippet provided: Web-based applications, fast development, shell scripts growing into libraries, and heavy backend data manipulation.
74. How would
if (isset($HTTP_POST_VARS)) from PHP look in Perl?Answer:
if ($ENV{'REQUEST_METHOD'} eq 'POST'){ ... }75. What is the output of
$p1 = "prog1.java"; $p1 =~ s/(.*)\.java/$1.cpp/; print "$p1\n";Answer:
prog1.cpp76. Which of these is a difference between C++ and Perl?
Answer: Perl can use closures with unreachable private data as objects. C++ supports pointer arithmetic allowing users to manipulate foreign objects, whereas Perl does not.
77. Why do you use Perl? / What is Perl?
Answer: It is a portable, flexible, high-level language with an eclectic heritage (C, sed, awk) that excels at text manipulation, quick prototyping, system utilities, and networking.
No comments:
Post a Comment