Perl Basics
- 1. What is CPAN? Its uses?CPAN stands for Comprehensive Perl Archive Network. It is a vast, centralized repository of Perl software, modules, and documentation. Its primary use is to allow developers to easily search, download, and install third-party libraries so they do not have to reinvent the wheel for common tasks (e.g., database connection, web scraping).2. What does “use strict”, “use vars”, “no vars” mean?
use strict: A compile-time pragma that forces you to declare variables before use (usually withmy), disables soft references, and forbids barewords, drastically reducing typos and logical errors.use vars: An older way to pre-declare global package variables, allowing you to use them underuse strictwithout getting an error. Modern Perl typically usesourinstead.no vars: Disables the effects of a previoususe varsdeclaration within the current scope.
3. Difference b/w use and require?use: Evaluated at compile-time. It loads the module and automatically calls itsimportmethod to bring functions/variables into your current namespace.require: Evaluated at run-time. It loads the module or file (if not already loaded) but does not call theimportmethod, meaning you must use fully qualified names to access its contents.
4. What do the symbols $ @ and % mean when prefixing a variable?$(Scalar): Holds a single, discrete value (a number, string, or reference).@(Array): Holds an ordered list of scalar values, indexed by numbers starting at 0.%(Hash): Holds an unordered set of key-value pairs, where keys are unique strings.
5. What purpose does each of the following serve: -w, strict, -T?-w: A command-line flag that enables run-time warnings for questionable code, such as using uninitialized variables.strict: A pragma that enforces strict variable declaration, references, and subroutines at compile-time.-T: Enables "Taint mode," a security feature that marks all data coming from outside the program (like user input or environment variables) as untrusted. Tainted data cannot be used in system calls or file operations until explicitly sanitized.
6. Explain the use of do, require, use, importdo: Executes a file as a Perl script or evaluates a block of code and returns the value of the last expression evaluated.require: Loads a Perl file or module into memory at run-time, ensuring it is only loaded once per script execution.use: Loads a module at compile-time and automatically invokes itsimportmethod.import: A method within a module that is responsible for exporting specific symbols (functions, variables) into the namespace of the script that calleduse.
7. Use of our, my and local?my: Creates a lexically scoped variable. It is entirely private to the block, loop, or subroutine where it is declared.our: Creates an alias to a package-scoped global variable, allowing you to access a global variable legally underuse strictwithout typing its full package name.local: Temporarily saves the current value of an existing global variable, assigns it a new value for the duration of the current block, and restores the original value when the block exits.
8. Use of ref functionThereffunction checks if a scalar variable is a reference. If it is, it returns a string indicating the type of data being referenced (e.g.,SCALAR,ARRAY,HASH,CODE, or the class/package name for blessed objects). If it is not a reference, it returns an empty string (false).9. What are STDIN, STDOUT and STDERR?These are the standard, pre-opened filehandles provided by the operating system:STDIN: Standard Input. Used to read data into the script (default is the keyboard).STDOUT: Standard Output. Used to print normal data out of the script (default is the terminal screen).STDERR: Standard Error. Used to print error messages or diagnostics (also defaults to the terminal screen, but can be redirected separately from STDOUT).
10. @INC and %INC@INC: A special built-in array that contains the list of directory paths Perl searches when it is told to load a module viauseorrequire.%INC: A special built-in hash where the keys are the names of the modules/files that have already been loaded, and the values are the absolute file paths to those modules on the system. Perl uses this to avoid loading the same file twice.
- 11. How you can invoke shell command? Hint: system(), backtick, exec() in details
system(): Runs the shell command in a child process, waits for it to complete, and then returns control to the Perl script. It returns the exit status of the command, not its output. Output goes directly to standard output (STDOUT).- Backticks (
`...`) orqx(): Executes the command and captures its standard output. It returns the output as a string (in scalar context) or as a list of lines (in list context) back to the Perl script. exec(): Replaces the currently running Perl process entirely with the new shell command. Control never returns to the Perl script after a successfulexec().
12. What is the exact difference between system() and exec()The exact difference lies in process flow.system()forks a new child process to run the command, allowing the Perl script to resume execution once the command finishes.exec()terminates the current Perl script completely and replaces it in memory with the executed command. Any code written below anexec()statement will never be reached unless the command fails to execute.13. Error handling using evalIn Perl, fatal errors (like callingdieor dividing by zero) normally crash the script. By wrapping risky code in aneval { ... }block, you trap the exception. The script continues running, and any error message is stored in the special variable$@. If$@is true after the block, it indicates an error occurred.14. Print the array @arr in reversed case-insensitive orderYou use thesortfunction with a custom block usingcmpandlc(lowercase), reversing the positions of$aand$b:print sort { lc($b) cmp lc($a) } @arr;15. There are two types of eval statements i.e. eval EXPR and eval BLOCK. Explain them.eval BLOCK(eval { ... }): Code within the block is checked for syntax at compile-time, making it highly efficient. It is standardly used for exception handling (trapping fatal errors).eval EXPR(eval "..."): Code within the string is parsed, compiled, and executed at run-time. It is much slower and can be a massive security risk if the string contains untrusted user input, but it allows for dynamic code generation.
16. Autovivification (very rarely)Autovivification is Perl's feature of automatically creating references, arrays, or hashes when an undefined variable is dereferenced. For example, if%hashis completely empty, saying$hash{Person}{Name} = "Alice";will automatically create the nested hash reference for{Person}on the fly.17. Questions on hash and hash referenceA hash (%hash) is a primary data structure containing key-value pairs. A hash reference ($href = \%hash) is a single scalar variable containing the memory address of a hash. References are required when building complex, nested data structures (like arrays of hashes) or when passing entire hashes into subroutines without flattening them into a list. 18. Sort a hash by values Sort the keys of the hash based on the comparison of their fetched values:my @sorted_keys = sort { $hash{$a} <=>$hash{$b} } keys \%hash;(Use<=>for numeric values, orcmpfor string values). 19. Length of a hash To get the number of key-value pairs in a hash, evaluate thekeysfunction in a scalar context:my $hash_length = scalar keys %hash;20. How to refer a hash and how to dereference it- Referencing: Use a backslash on a named hash (
my $href = \%hash;) or create an anonymous hash reference (my $href = { key => 'value' };). - Dereferencing: Use the arrow operator for single values (
$href->{key}) or the\%sigil to extract the whole hash (\%{$href}).
21. Nesting of hashBecause Perl hashes can only store scalar values, you cannot place a literal hash inside another hash. To nest, you must use hash references as the values of the outer hash's keys:$company{IT} = { Manager => 'Bob', Headcount => 15 };22. Chomp and chop *chop: Blindly removes and returns the absolute last character of a string, no matter what it is. *chomp: Safely removes the trailing newline character (the current value of$/) from the end of a string. If there is no newline, it does nothing. It returns the number of characters removed.23. Explain qw, qq, qx (what’s its use, when to use)qw(...): Quote Words. Automatically extracts whitespace-separated words into a list. (e.g.,qw(red blue)is exactly identical to('red', 'blue')). Use it to type lists faster without commas or quotes.qq(...): Double-quote. Acts exactly like standard double quotes ("..."), interpolating variables within the string. Useful if your string contains literal quote marks so you don't have to escape them.qx(...): Quote Execute. Acts exactly like backticks (`...`) to execute a system command and return its output into the script. Useful for avoiding escaping issues with commands containing quotes.
- 24. What are the different ways to concatenate strings in Perl
- Dot Operator (
.): The standard string concatenation operator. Example:$result = $str1 . $str2; - Double-quote Interpolation: Embedding variables directly within double quotes. Example:
$result = "$str1$str2"; joinfunction: Best for combining an array of strings. Example:$result = join("", $str1, $str2);.=Operator: Appends a string to an existing variable. Example:$str1 .= $str2;
25. Functions on array: Push, pop, shift, unshift, join, split, splicepush: Appends one or more elements to the end of an array.pop: Removes and returns the last element of an array.shift: Removes and returns the first element of an array, shifting all other elements left.unshift: Prepends one or more elements to the beginning of an array, shifting existing elements right.join: Concatenates array elements into a single string, separated by a specified delimiter.split: Breaks a string into an array of substrings using a regular expression as the delimiter.splice: The most powerful array manipulator; it can add, remove, or replace elements anywhere within an array.
26. Different hash functions like each, keys, values, exists, deletekeys: Returns a list of all the keys in a hash.values: Returns a list of all the values in a hash.each: Iterates through a hash, returning a 2-element list containing the next key and value.exists: Returns true if a specified key exists in the hash, regardless of whether its value is defined orundef.delete: Removes a key and its associated value from the hash entirely.
27. Numeric and string sorting of hash and array elements in PerlThesortfunction relies on a block to determine comparison rules:- String sorting: Uses the
cmpoperator. Example:sort { $a cmp $b } @arr;(This is also the default if no block is provided). - Numeric sorting: Uses the
<=>operator. Example:sort { $a <=> $b } @arr; - Hash sorting: Hashes cannot be sorted directly. You must sort their
keys(often by comparing their values inside the sort block) and then iterate through the sorted keys.
28. How to set Environment variables in Perl (Hint: %ENV)Environment variables are accessed and modified using the special global hash%ENV.$ENV{'PATH'} = '/my/custom/path:' . $ENV{'PATH'};Changes made to%ENVonly affect the current Perl process and any child processes (like system commands) it spawns; they do not alter the parent shell's environment.29. Use of map and grep functions in Perlmap(Transformation): Applies an expression or block of code to every element in a list, returning a new list containing the results. Example:my @squares = map { $_ * $_ } @numbers;grep(Filtering): Evaluates an expression or block for every element in a list, returning a new list containing only the elements for which the expression returned true. Example:my @evens = grep { $_ % 2 == 0 } @numbers;
30. What is the difference between die and exit in perldie: Throws a fatal exception and prints an error message toSTDERR. It is used for error handling and its execution can be intercepted/caught using anevalblock.exit: Terminates the program normally and immediately returns a specific exit status code to the operating system. It is not an exception and cannot be caught byeval.
31. Array with repeating digits. Sort and print digits with no of counts. (No hash allowed, optimize)To achieve the exact output array(1,1,1,2,2,2,3,3,4,4,4,6,6,8,9), you simply use a numeric sort, which takes $O(N \log N)$ time:@arr = sort { $a <=> $b } @arr;If the goal is to also print the unique digits alongside their occurrence count without using a hash (which would take $O(N)$ time but is forbidden by the prompt), you can sort the array first, then iterate through it sequentially. This takes $O(N \log N)$ time and $O(1)$ auxiliary space:my @arr = (1,2,4,6,3,1,2,6,8,3,4,9,1,2,4); @arr = sort { $a <=> $b } @arr; my $count = 1; for (my $i = 0; $i < @arr; $i++) { if ($i < $#arr && $arr[$i] == $arr[$i+1]) { $count++; } else { print "Digit: $arr[$i], Count: $count\n"; $count = 1; # Reset for the next digit } }32. Write a Perl script for decimal to binary, decimal to octal, decimal to hex, hex to decimal, hex to octal, hex to binaryPerl handles conversions efficiently usingsprintffor formatting numbers into strings (binary, octal, hex) andhex()oroct()for converting strings back to decimal numbers.my $dec = 255; # Decimal to Others my $bin_str = sprintf("%b", $dec); # "11111111" my $oct_str = sprintf("%o", $dec); # "377" my $hex_str = sprintf("%x", $dec); # "ff" # Others to Decimal my $dec_from_hex = hex($hex_str); # 255 my $dec_from_oct = oct($oct_str); # 255 my $dec_from_bin = oct("0b" . $bin_str); # 255 # Hex to Binary/Octal (Convert Hex to Decimal first, then format) my $hex_to_bin = sprintf("%b", hex($hex_str));
my $hex_to_oct = sprintf("%o", hex($hex_str)); - 33. How to find which method is being invoked or being called in Perl and in which method you are currently? (Hint: caller())You can use the built-in
caller()function to inspect the call stack.- To find out information about the current subroutine's caller (who invoked you), use
caller(0). - To find the name of the method you are currently in, you look one level deeper in the stack using
caller(0)from a nested context, or typically(caller(0))[3]to get the subroutine name of the currently executing frame.Example:my ($package, $filename, $line, $subroutine) = caller(0);
34. Explain the use of caller and wantarray function?caller: Used to return information about the stack of current subroutine calls. It provides the package name, file name, line number, and subroutine name of the code that called the current function. It is highly useful for debugging and generating stack traces.wantarray: Detects the context in which a subroutine was called. It returns true (1) if the subroutine was called in a list context, false ("") if called in a scalar context, andundefif called in a void context (where the return value is discarded). This allows a subroutine to return different, context-appropriate data.
35. How will you find line number, package and a file name in Perl? (Hint: __FILE__, __LINE__, __PACKAGE__)You use Perl's special compile-time tokens:__LINE__: Returns the current line number of the script where the token is written.__FILE__: Returns the name of the current file being executed.__PACKAGE__: Returns the name of the current package being compiled (defaults tomain).
36. How to install a Perl Module from CPANFrom your system's command line, you can use the standard CPAN shell:cpan Module::NameAlternatively, many developers prefercpanm(CPAN Minus) for a quieter, more streamlined installation:cpanm Module::Name37. Pass an array to subroutine and get it as an array ref in sub. Hint: subroutine prototype. Ex: sub subname(@)By using the(\@)prototype, you force Perl to pass the array as a reference implicitly, without the caller needing to explicitly use the backslash\@arraysyntax.sub process_array (\@) { my $array_ref = shift; print "First element: $array_ref->[0]\n"; } my @data = (10, 20, 30); process_array(@data); # Passed implicitly as a reference38. You have two arrays. Say @arr1 = (1,2,5,6) and @arr2 = (3,4). Put the element of @arr2 at @arr1 so @arr1 becomes (1,2,3,4,5,6) without using a third array. Hint: use spliceThesplicefunction can insert elements into an array at a specific offset. You want to insert@arr2starting at index 2, removing 0 elements.my @arr1 = (1, 2, 5, 6); my @arr2 = (3, 4); splice(@arr1, 2, 0, @arr2); # @arr1 is now (1, 2, 3, 4, 5, 6)39. Inbuilt special variable like $!,$? Etc$!: The system error message (orerrno). It returns the numeric error code in a numeric context, or the string error message (like "File not found") in a string context after a failed system call or I/O operation. *$?: The status returned by the last pipe close, backtick (`) command, orsystem()operator. To get the actual exit value, you typically divide it by 256 ($? >> 8).$_: The default input and pattern-matching space (often called the "it" variable).$@: The Perl syntax error message from the lasteval()block.
40. Piping in and piping out in PerlPiping allows Perl to stream data to or from external system commands using theopenfunction.- Piping In (Read from a command): Open a filehandle with a trailing pipe.
open(my $in, '-|', 'ls -l') or die; - Piping Out (Write to a command): Open a filehandle with a leading pipe.
open(my $out, '|-', 'grep error') or die;
41. How to implement stack and queue in Perl?Perl arrays act natively as both stacks and queues using standard array functions.- Stack (LIFO - Last In, First Out): Use
pushto add elements to the top, andpopto remove them from the top. - Queue (FIFO - First In, First Out): Use
pushto add elements to the back, andshiftto remove them from the front.
42. How to find the list of installed modules in Perl?You can check the locally installed modules via the command line usingperldoc:perldoc perllocalAlternatively, you can use theinstmodshutility bundled with ExtUtils::MakeMaker, or run a one-liner to search through the@INCpath for.pmfiles.43. Use of BEGIN and END block.BEGIN { ... }: Executes its code immediately as soon as the block is parsed during the compile phase, before the rest of the script is compiled or executed. Useful for modifying@INCor verifying dependencies early.END { ... }: Executes as late as possible, right before the Perl interpreter exits. Useful for cleanup tasks, closing database connections, or deleting temporary files, even if the script terminates viadie().
44. Simulate the behaviour of ‘use lib’ pragma using BEGIN block.Theuse lib '/path/to/dir'pragma simply unshifts a directory path onto the@INCarray at compile time. You can manually simulate this behavior exactly like this:BEGIN { unshift @INC, '/path/to/dir'; }
File Handling in Perl
- 45. File Testing. Binary or text, size, accessed like –e, -f, -a, -c –m etcPerl provides a suite of file test operators that perform checks on files and directories, returning true or false (or specific values like size or age).
-e: File or directory exists.-f: Is a plain file.-d: Is a directory.-s: Returns the size of the file in bytes (and evaluates to true if the size is greater than zero).-T/-B: Tests if the file is a text (-T) or binary (-B) file.-M: Returns the script's start time minus the file's last modification time, in days.-A: Returns the script's start time minus the file's last access time, in days.-C: Returns the script's start time minus the file's inode change time, in days.
46. Use of the special file handle _. (Note: it's just _ not $_)When you perform a file test (like-eor-M) or astaton a file, Perl executes an expensive system call to fetch the file's metadata, which it then caches in memory. The special filehandle_(underscore) tells Perl to reuse the cachedstatinformation from the very last file test rather than making a fresh system call.Example:if (-f $file && -s _ < 1024)checks if it's a plain file, and if so, reuses the cache to check if its size is under 1KB, boosting performance significantly.47. Syntax for opening, appending, reading, writing filesModern Perl uses the three-argumentopenfunction with lexical filehandles:- Reading (
<):open(my $fh, '<', 'filename.txt') or die "Cannot open: $!"; - Writing (
>):open(my $fh, '>', 'filename.txt') or die "Cannot open: $!";(This truncates/overwrites existing content). - Appending (
>>):open(my $fh, '>>', 'filename.txt') or die "Cannot open: $!";(This adds to the end of an existing file).
48. How to assign File handle into an array instead of using while loop?You can read the entire contents of a filehandle into an array simply by evaluating the filehandle in a list context. Each element of the array will contain one line of the file (including the newline character).my @lines = <$fh>;(Note: This is memory-intensive for very large files, hence whywhile (<$fh>)is generally preferred).49. How to delete a file?Use the built-inunlinkfunction, which deletes a list of files and returns the number of files successfully deleted.unlink('file.txt') or die "Could not delete: $!";50. How to copy or move a file?Perl handles this best via the standardFile::Copymodule.- Copy:
use File::Copy; copy("source.txt", "destination.txt") or die "Copy failed: $!"; - Move:
use File::Copy; move("old_name.txt", "new_name.txt") or die "Move failed: $!";
(You can also use the built-inrename("old", "new")function to move a file, but it may fail if you try to move a file across different filesystem partitions, whereasFile::Copy::movehandles this gracefully).51. What the various file permissions (flags) in Perl?Permissions can be checked using specific file test operators, or modified using thechmodfunction.- Test Operators:
-r: File is readable by the effective uid/gid.-w: File is writable by the effective uid/gid.-x: File is executable by the effective uid/gid.-o: File is owned by the effective uid.
- Setting Permissions: Use
chmodwith an octal number.chmod(0755, 'script.pl') or die "Couldn't chmod: $!";
52. Given a file, count the word occurrence (case insensitive)You can read the file line by line, convert each line to lowercase, split it into words using a regular expression, and populate a hash to track the counts.my %word_count; open(my $fh, '<', 'text.txt') or die $!; while (my $line = <$fh>) { # Extract words (alphanumeric sequences), ignoring punctuation my @words = split(/\W+/, lc($line)); foreach my $word (@words) { $word_count{$word}++ if $word ne ''; # Skip empty strings } } # Display results while (my ($word, $count) = each %word_count) { print "$word: $count\n"; }53. Displaying file contents using hash in PerlThis typically implies reading a file containing key-value pairs (like a configuration file) and storing it in a hash for easy display or lookup.my %config; open(my $fh, '<', 'config.txt') or die $!; # Assuming file format is: Key=Value while (my $line = <$fh>) { chomp $line; my ($key, $value) = split(/=/, $line, 2); $config{$key} = $value if defined $key; } # Displaying the contents foreach my $k (keys %config) { print "$k => $config{$k}\n"; }
Web based & Perl CGI
- 54. What do you know about CGI.pm?CGI.pm is a large, historically significant Perl module used for building Common Gateway Interface (CGI) web applications. It provides a robust API for parsing incoming HTTP request data (handling both GET and POST variables seamlessly), managing cookies, and generating HTTP headers. While it also contains methods for generating HTML tags, this practice is largely outdated. Note that as of Perl 5.22, CGI.pm was removed from the Perl core distribution, and modern Perl web development typically favors frameworks like Mojolicious, Dancer, or Catalyst.55. How to set sessions and cookies and how to implement in Perl?
- Cookies: You implement cookies using the
CGImodule to generate a cookie object, which is then passed to the HTTP header.use CGI; my $q = CGI->new; my $cookie = $q->cookie( -name => 'username', -value => 'alice123', -expires => '+1h' ); print $q->header(-cookie => $cookie); - Sessions: Sessions are generally implemented using the
CGI::Sessionmodule alongsideCGI.CGI::Sessionhandles the backend storage (like a file or database) and automatically generates a unique Session ID, which you send to the client via a cookie.use CGI; use CGI::Session; my $q = CGI->new; # Create a new session (or retrieve an existing one based on the incoming cookie) my $session = CGI::Session->new(undef, $q, {Directory=>'/tmp'}); # Store data on the server side $session->param('role', 'admin'); # Send the session ID to the user as a cookie my $cookie = $q->cookie(CGISESSID => $session->id); print $q->header(-cookie => $cookie);
56. How to display JSON based outputTo serve JSON, you need to use a module likeJSONorJSON::XSto serialize your Perl data structures (like hashes or arrays) into a JSON-formatted string. Crucially, you must also change the HTTPContent-Typeheader fromtext/htmltoapplication/json.use strict; use warnings; use JSON; my %data = ( status => 'success', user_id => 101, message => 'Data loaded successfully' ); # Convert the Perl hash to a JSON string my $json_output = encode_json(\%data); # Print the correct HTTP header, followed by the blank line, then the JSON print "Content-Type: application/json\n\n"; print $json_output;57. Why two \n in print “Content-type: text/html \n\n”;The HTTP protocol specification dictates that the HTTP response headers and the actual response body (the HTML content, JSON data, etc.) must be separated by a completely blank line.- The first
\nterminates theContent-type: text/htmlheader line. - The second
\ncreates the required blank line, signaling to the receiving web browser that the headers have ended and the page content is about to begin. Without the second newline, the browser will fail to render the page, treating your content as malformed headers resulting in an "Internal Server Error" or a blank screen.
Database oriented
- 58. How to connect database using DBI?To connect to a database in Perl, use the
DBI(Database Interface) module and call itsconnectmethod. You must provide a Data Source Name (DSN) string, the database username, the password, and optionally a hash reference of connection attributes (such as enabling exceptions withRaiseError).use DBI; my $dsn = "DBI:mysql:database=my_db;host=localhost"; my $username = "db_user"; my $password = "db_pass"; my %attributes = ( RaiseError => 1, AutoCommit => 1 ); my $dbh = DBI->connect($dsn, $username, $password, \%attributes) or die "Connection failed: " . DBI->errstr;59. What are the ways you know to get records from the table (fetchrow_hashref/arrayref)?After preparing and executing a SQL query to get a statement handle ($sth), you can fetch records using several methods depending on how you want the data structured:fetchrow_array(): Returns the next row of data as a standard Perl list (array) of values.my @row = $sth->fetchrow_array();fetchrow_arrayref()(or its aliasfetch()): Returns the next row as a reference to an array. It is faster and uses less memory thanfetchrow_array()because it avoids copying the data into a new list.my $array_ref = $sth->fetchrow_arrayref();fetchrow_hashref(): Returns the next row as a reference to a hash, where the hash keys are the database column names and the values are the row data. It is highly readable but slightly slower than array fetching.my $hash_ref = $sth->fetchrow_hashref();fetchall_arrayref(): Fetches all remaining rows from the query at once and returns a reference to an array of array references.my $all_data = $sth->fetchall_arrayref();fetchall_hashref('key_column'): Fetches all remaining rows and returns a reference to a hash of hash references, using a specified column's values as the primary keys for the outer hash.my $all_hash_data = $sth->fetchall_hashref('id');bind_columns(): For maximum performance, you bind specific Perl variables to the result columns before looping, so the variables are automatically updated on each call tofetch().
Object Oriented Perl
- 60. Diff b/w module and package
- Package: A namespace in Perl that separates your variables and subroutines from those in other namespaces to prevent naming collisions. It is declared using the
packagekeyword. - Module: A physical file (usually with a
.pmextension) that contains reusable Perl code. A single module file usually defines one package (with a matching name), but technically it can contain multiplepackagedeclarations.
61. Diff b/w class and package (rarely asked though )In Perl's traditional object-oriented system, there is no syntactical difference between a class and a package; a class is just a package. A package functions as a class when it contains subroutines designed to act as methods (where they expect an object reference or class name as their first argument) and when objects areblessed into its namespace.62. How do you call any subroutine in object oriented fashion? Hint: bless operatorTo call a subroutine in an object-oriented way, you must first create a reference (usually a hash reference) and use theblessoperator to associate it with a specific package (class).# In MyClass.pmpackage MyClass; sub new { my $class = shift; my $self = {}; bless $self, $class; # Associates the hash reference with MyClass return $self; } sub display { my $self = shift; # The object itself is passed as the first argument print "Hello from OOP\n"; } # In the calling script my $obj = MyClass->new(); $obj->display(); # Calls the subroutine in an OO fashion using the arrow operator63. Use base, EXPORT, EXPORT_OKuse base 'ParentClass': Establishes inheritance. It loads the specified module at compile-time and automatically addsParentClassto the current package's@ISAarray, meaning the current class will inherit methods fromParentClass.@EXPORT: An array used by theExportermodule. Any subroutines or variables listed here are exported automatically into the calling script's namespace when it runsuse YourModule;. This can cause namespace pollution.@EXPORT_OK: An array for on-demand exporting. Symbols listed here are only exported if the calling script explicitly requests them (e.g.,use YourModule qw(specific_function);).
64. Difference between ISA and EXPORT@ISA: Used for Object-Oriented inheritance. It defines the "is-a" relationship. If a method is called on an object but not found in its class, Perl looks through the classes listed in@ISAto find the method. It does not copy subroutines into your namespace.@EXPORT: Used for Procedural programming. It physically copies subroutines and variables from a module's namespace directly into the caller's namespace, allowing them to be called like local functions.
65. Use Base related questionsQuestions surroundinguse baseusually focus on how Perl handles multiple inheritance and method resolution. When you douse base qw(ClassA ClassB);, Perl searches for missing methods depth-first, left-to-right.(Note: In modern Perl development, theuse parentpragma is widely preferred overuse baseas it is lighter and avoids some historical edge cases associated withuse base).66. Use of AUTOLOAD function.AUTOLOADis a special fallback subroutine in Perl. If you attempt to call a method on an object or class, and Perl cannot find that method anywhere in the class or its@ISAhierarchy, it will check if anAUTOLOADsubroutine exists in the package. If it does, Perl invokesAUTOLOADinstead of throwing a fatal "Can't locate object method" error. The fully qualified name of the missing method is automatically stored in the special package variable$AUTOLOAD. It is frequently used for dynamically generating getters and setters for object attributes on the fly.
Regular Expression in Perl
- 67. IP Address validationA robust regular expression to validate an IPv4 address (ensuring each octet is strictly between 0 and 255):
my $ip = "192.168.1.1"; if ($ip =~ /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/) { print "Valid IP\n"; }(For simple formatting checks without numeric range validation,^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$is sometimes used, but it is less accurate).68. Email id ValidationA basic regular expression to check standard email formatting:my $email = "test@example.com"; if ($email =~ /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/) { print "Valid Email\n"; }(Note: For production environments, using a dedicated module likeEmail::Validis highly recommended over writing custom email regex).69. More than one @ is there. Give regex to store username and domain name after encountering last @ (Last @ will be the splitting point and more than one special characters can be there)Because Perl's*quantifier is greedy by default,.*will automatically consume everything up to the final@symbol in the string.my $str = "user\@name\@domain.com"; if (my ($username, $domain) = $str =~ /^(.*)@([^@]+)$/) { print "Username: $username\n"; # Outputs: user@name print "Domain: $domain\n"; # Outputs: domain.com }70. What are the uses of different modifiersModifiers are appended to the end of a regex (e.g.,/pattern/i) to change how the matching engine behaves:i(Case-insensitive): Ignores uppercase and lowercase distinctions.g(Global): Finds all matches in the string, rather than stopping after the first match.m(Multi-line): Changes^and$to match the start and end of any line within a multi-line string, rather than just the absolute start and end of the string.s(Single-line): Forces the dot (.) metacharacter to match newline characters (\n), treating the whole string as a single continuous line.x(Extended): Ignores whitespace within the regex pattern and allows comments (using#), making complex patterns readable.
71. Group, range, meta-character etc- Group
(): Parentheses group parts of a pattern together. They also "capture" the matched text into special memory variables ($1,$2, etc.) for later extraction or substitution. - Range
[]: Brackets define a character class, matching any single character contained within. You can define a range using a hyphen (e.g.,[a-z]matches any lowercase letter,[0-9]matches any digit). - Meta-character: Characters that hold special meaning to the regex engine rather than representing literal characters. Examples include
^,$,.,*,+,?,|,\,(,),[,],{,}. To use them literally, they must be escaped with a backslash (e.g.,\$).
72. m, s, trm//(Match): Used to search a string for a specific pattern. Themis optional if you use standard forward slashes (e.g.,/pattern/).s///(Substitute): Used to search for a pattern and replace it with a new string. (e.g.,s/old/new/).tr///ory///(Transliteration/Translation): Translates characters one-by-one. It does not use regular expressions. For example,tr/a-z/A-Z/replaces all lowercase letters with their uppercase equivalents.
73. Replace the last ‘x’ in a string with ‘ax’ in one regex. Example : abcxdefgxgaxa should become abcxdefgxgaaxaYou can achieve this effortlessly using a Negative Lookahead(?!...), which asserts that there are no morexcharacters ahead in the string:Perlmy $str = "abcxdefgxgaxa"; $str =~ s/x(?!.*x)/ax/; # Result: abcxdefgxgaaxaAlternatively, using greediness and capture groups:$str =~ s/(.*)x/$1ax/s;74. Perl regular expression is greedy. Can you explain it with one example?"Greedy" means quantifiers like*(zero or more) and+(one or more) will attempt to match as much text as physically possible while still allowing the overall pattern to succeed.- Example: Let
$str = "<div>Hello</div><div>World</div>"; - Greedy (Default): If we match
m/<div>(.*)<\/div>/, the.*is greedy. It grabsHello</div><div>World, stopping only at the absolute final closing tag. - Non-Greedy (Reluctant): By appending a
?quantifier, we make it lazy:m/<div>(.*?)<\/div>/. Now it stops at the very first closing tag it sees, capturing onlyHello.
75. Can you check palindrome condition using regular expression in perl? (Hint: regex doesn’t support recursion or counting facility)Based on traditional Regular Expression theory (and the constraint of the hint), no. Standard regular expressions represent finite state automata, which have no memory to "count" the length of a string or pair up nested boundary characters infinitely.(Note: While you can write a hardcoded regex for a palindrome of a specific, fixed length using backreferences like/(.)(.)(.)\2\1/, you cannot write a single traditional regex for a palindrome of arbitrary length. The standard Perl solution is to simply use the built-in string reverse function:if ($str eq reverse($str)) { ... }).
Perl One Liner
- 76. What is Perl one liner and where you will use it?A Perl one-liner is a short, concise Perl script designed to fit on a single command line and be executed directly from the terminal without creating a dedicated
.plfile. They are primarily used for quick text processing, data extraction, search-and-replace operations across multiple files, and system administration tasks where writing a full script would be overkill.77. What are the different options in Perl one Liner. Explain in details-e: Specifies that the immediate following string is the Perl code to execute.-n: Wraps the code in awhile (<>) { ... }loop, reading the input line by line into the$_variable, but does not automatically print anything.-p: Similar to-n, but it automatically prints the contents of$_after executing your code for each line.-i: Edits the file in-place. If you provide an extension (like-i.bak), it creates a backup of the original file before modifying it.-a: Autosplit mode. Used with-nor-p, it automatically splits the input line by whitespace and stores the result in the@Farray.-F: Specifies the delimiter pattern to use for the-aoption (e.g.,-F:splits by colons).-l: Enables automatic line-ending processing. It automaticallychomps the input lines and appends a newline character to anyprintstatements.
78. Add a blank line before every line.Use the-pflag and modify$_to include a leading newline:perl -pe 's/^/\n/' file.txt(Alternatively:perl -pe '$_ = "\n$_"' file.txt)79. Remove blank lines form a file.Use the-nflag and tell Perl to print the line only if it contains non-whitespace characters (\S):perl -ne 'print if /\S/' file.txt(To also remove lines that are completely empty but keep lines with spaces:perl -ne 'print if /./' file.txt)80. Print the total number of lines in a file (emulate wc -l).You can use the special variable$.which holds the current line number, and print it at theENDblock after the file has been fully read:perl -lne 'END { print $. }' file.txt81. Print the number of non-empty lines in a file.Increment a counter only if the line contains non-whitespace characters, and print it at the end:perl -lne '$count++ if /\S/; END { print $count+0 }' file.txt82. What option you will use to check syntax only without executing it?The-cflag checks the syntax of the script or one-liner and reports errors without actually running the program code:perl -c script.pl83. Which option is meant to enable all warnings or disable all warning inpite of using use warning or no warnings respectively?- Enable warnings: The
-wflag globally enables warnings, and-Wforces all warnings on unconditionally (overridingno warnings). - Disable warnings: The
-Xflag unconditionally disables all warnings, overriding anyuse warningspragmas inside the code.
No comments:
Post a Comment