Perl Interview question and answers 2023
Collection of resources for anyone preparing for a Perl programming interview. These frequently asked questions and their detailed answers cover topics such as Perl syntax, data types, control structures, regular expressions, object-oriented programming, and more.
Perl Basics
1. What is Perl?
Perl is a high-level programming language that was originally designed for text manipulation and is known for its powerful regular expression capabilities. It was created by Larry Wall in 1987 and has since evolved into a versatile language used for a wide range of tasks, including system administration, web development, database programming, and more.
Perl is a cross-platform language, meaning that it can be run on a variety of operating systems, including Linux, Windows, macOS, and more. It is an interpreted language, which means that code written in Perl is executed directly by the interpreter, rather than being compiled into machine code beforehand.
Perl is also notable for its large and active community of developers, who have created a vast library of modules and extensions to the language, making it easy to build complex applications quickly and efficiently. Overall, Perl is a powerful and flexible language that has become a staple of many industries and continues to evolve to meet new challenges.
2. How do you comment on single or multiple lines of code in Perl?
In Perl, you can comment on a single line of code by starting the line with the ‘#’ character.
Example :
# This is a comment in Perl
print "Hello, World!\n"; # This line prints "Hello, World!"
To comment on multiple lines of code, you can use the =head and =cut directives to create a block of documentation. Any code between these directives will be ignored by the interpreter.
Example :
=head
print "Welcome\n";
print "Hello, World!\n";
=cut
3. What is the difference between single and double quotes in Perl?
Single quotes
Single quotes are not interpolated string literals, meaning that they lose their meaning.
Example :
my $value = 45;
print 'The value is $value \n';
#output
The value is $value #it will not print the 45 beacuse it lose their meaning.
Double quotes
Double quotes are interpolated string literals, meaning that they not lose their meaning.
Example :
my $value = 45;
print "The value is $value \n";
#output
The value is 45 #it will print the 45 beacuse it not lose their meaning.
In double quotes we need to lose the meaning then use black slash (\)
Example :
my $value = 45;
print "The value is \$value"
#output
The value is $value #it will not print the 45 beacuse it lose their meaning.
4. What are the data types in Perl?
There are 3 data types
- scalar
- hash
- array
5. Can you explain the scalar data type in Perl?
In Perl, a scalar is a variable that can hold a single value of one of several different data types.
scalars are variables that can hold a single value of various data types, including numbers, strings, booleans, and undefined values. They are declared using the $ symbol followed by the variable name and can be assigned and accessed using the standard variable assignment and access syntax.
Example :
my $name = "Suraj"; # Declares a scalar variable named $name with the value "Alice"
my $age = 24; # Declares a scalar variable named $age with the value 30
my $is_developer = 1; # Declares a scalar variable named $is_student with the value 1 (true)
my $address; # Declares a scalar variable named $address with an undefined value
You can assign a value to a scalar variable using the assignment operator “ = “
Example :
$name = "Vijay"; # Assigns the value "Vijay" to the $name variable
$age = $age + 1; # Increments the value of $age by 1
$is_developer = 0; # Assigns the value 0 (false) to $is_developer
You can access the value of a scalar variable by simply using its name.
print $name; # Prints the value of $name (currently "Bob")
print $age; # Prints the value of $age (currently 31)
print $is_developer # Prints the value of $is_developer(currently 0)
6. Can you explain the hash data type in Perl?
In Perl, a hash is a data structure that allows you to associate keys with values, similar to a dictionary or map in other programming languages. Each key in a hash is unique and corresponds to a single value.
Hashes are declared using the % symbol followed by the variable name
Example :
my %person = (
"name" => "Suraj",
"age" => 24,
"is_developer" => 1
);
In this example, we have declared a hash named %person with three keys (“name”, “age”, and “is_student”), each of which corresponds to a value.
You can access the value of a hash element using the key name in square brackets
Example :
print $person{"name"}; # Prints the value of the "name" key (currently "Alice")
print $person{"age"}; # Prints the value of the "age" key (currently 30)
print $person{"is_developer"}; # Prints the value of the "is_student" key (currently 1)
You can also assign a new value to a hash element using the key name and the assignment operator ‘=’.
$person{"name"} = "Bob"; # Assigns the value "Bob" to the "name" key
$person{"age"} = $person{"age"} + 1; # Increments the value of the "age" key by 1
$person{"is_developer"} = 0; # Assigns the value 0 (false) to the "is_student" key
7. Can you explain the array data type in Perl?
In Perl, an array is a data structure that can store a collection of values. Each value in an array is assigned a numeric index, starting from 0 for the first element, and increasing by 1 for each subsequent element.
Arrays are declared using the @ symbol followed by the variable name.
Example :
my @numbers = (1, 2, 3, 4, 5);
In this example, we have declared an array named @numbers with five elements, each of which corresponds to a numeric index.
You can access the value of an array element using the numeric index in square brackets.
Example :
print $numbers[0]; # Prints the first element of the array (currently 1)
print $numbers[2]; # Prints the third element of the array (currently 3)
print $numbers[4]; # Prints the fifth element of the array (currently 5)
You can also assign a new value to an array element using the numeric index and the assignment operator ‘=’.
$numbers[0] = 10; # Assigns the value 10 to the first element of the array
$numbers[2] = $numbers[2] + 1; # Increments the value of the third element of the array by 1
$numbers[4] = "five"; # Assigns the string "five" to the fifth element of the array
8. What are some scalar datatype operations in Perl?
Here are some of the most common scalar datatype operations in Perl:
1. Assignment: The assignment operator “=” is used to assign a value to a scalar variable.
Example :
my $num = 10;
my $str = "Hello, world!";
2. Arithmetic operators: Perl provides a variety of arithmetic operators for scalar variables, including “+”, “-”, “*”, “/”, and “%”.
Example :
my $a = 10;
my $b = 5;
my $sum = $a + $b;
my $diff = $a - $b;
my $prod = $a * $b;
my $quot = $a / $b;
my $mod = $a % $b;
3. String operators: Perl provides several operators for working with strings, including concatenation (“.”) and repetition (“x”).
Example :
my $str1 = "Hello, ";
my $str2 = "world!";
my $str3 = $str1 . $str2; # Concatenation, Output : Hello, world!
my $str4 = $str1 x 3; # Repetition Output : Hello, Hello, Hello,
4. Comparison operators: Perl provides several comparison operators for scalar variables, including “==”, “!=”, “<”, “<=”, “>”, and “>=”.
Example :
my $a = 10;
my $b = 5;
my $result1 = $a == $b; # Equality
my $result2 = $a != $b; # Inequality
my $result3 = $a > $b; # Greater than
my $result4 = $a <= $b; # Less than or equal to
5. Logical operators: Perl provides several logical operators for scalar variables, including “&&” (logical AND), “||” (logical OR), and “!” (logical NOT).
Example:
my $a = 10;
my $b = 5;
my $result1 = $a > $b && $a < 20; # Logical AND
my $result2 = $a < $b || $a == 10; # Logical OR
my $result3 = !($a == $b); # Logical NOT
9. What are the array methods in Perl?
1. push(): Adds one or more elements to the end of an array.
my @fruits = ('apple', 'banana');
push(@fruits, 'orange');
print "@fruits"; # Output: apple banana orange
2. pop(): Removes and returns the last element of an array.
my @fruits = ('apple', 'banana', 'orange');
my $last_fruit = pop(@fruits);
print "$last_fruit"; # Output: orange
3. shift(): Removes and returns the first element of an array.
my @fruits = ('apple', 'banana', 'orange');
my $first_fruit = shift(@fruits);
print "$first_fruit"; # Output: apple
4. unshift(): Adds one or more elements to the beginning of an array.
my @fruits = ('banana', 'orange');
unshift(@fruits, 'apple');
print "@fruits"; # Output: apple banana orange
5. splice(): Removes or replaces a portion of an array.
my @fruits = ('apple', 'banana', 'orange', 'grape', 'kiwi');
splice(@fruits, 2, 2, 'pear', 'peach');
print "@fruits"; # Output: apple banana pear peach kiwi
6. join(): Concatenates the elements of an array into a single string, using a specified delimiter.
my @fruits = ('apple', 'banana', 'orange');
my $fruits_string = join(', ', @fruits);
print "$fruits_string"; # Output: apple, banana, orange
7. split(): Splits a string into an array, using a specified delimiter.
my $fruits_string = 'apple, banana, orange';
my @fruits = split(', ', $fruits_string);
print "@fruits"; # Output: apple banana orange
8. sort(): Sorts the elements of an array in ascending order.
my @fruits = ('banana', 'orange', 'apple');
my @sorted_fruits = sort(@fruits);
print "@sorted_fruits"; # Output: apple banana orange
9. reverse(): Reverses the order of elements in an array.
my @fruits = ('apple', 'banana', 'orange');
my @reversed_fruits = reverse(@fruits);
print "@reversed_fruits"; # Output: orange banana apple
10. grep(): Returns a list of all elements in an array that match a specified condition.
my @fruits = ('apple', 'banana', 'orange', 'pear', 'peach');
my @selected_fruits = grep(/p/, @fruits);
print "@selected_fruits"; # Output: apple grape peach
11. map(): Returns a new list of elements that result from applying a function to each element in an array.
my @fruits = ('apple', 'banana', 'orange');
my @uppercase_fruits = map(uc, @fruits);
print "@uppercase_fruits"; # Output: APPLE BANANA ORANGE
12. slice(): Returns a specified portion of an array as a new array.
my @fruits = ('apple', 'banana', 'orange', 'pear', 'peach');
my @selected_fruits = @fruits[1..3];
print "@selected_fruits"; # Output: banana orange pear
10. How can you reset the starting index of an array in Perl?
In Perl, you can reset the starting index of an array by changing the value of the $[ variable. By default, the starting index of arrays in Perl is 0, but you can change it to any integer value.
However, it is not recommended to use `$[` in modern Perl programming because it can cause confusion and make code harder to maintain. Instead, you can use the use feature ‘array_base’; pragma to set the starting index of arrays in a Perl script.
Here’s an example of how to reset the starting index of an array to 1 in Perl:
use feature 'array_base';
$[ = 1; # set starting index of arrays to 1my @fruits = ('apple', 'banana', 'orange');
print "$fruits[1]\n"; # Output: apple
print "$fruits[2]\n"; # Output: banana
print "$fruits[3]\n"; # Output: orange
11. What is the difference between chop and chomp in Perl?
chop and chomp are two Perl built-in functions that are used to remove characters from the end of a string. However, there is a difference in how they work.
chop:
chop removes the last character of a string, regardless of what it is. It modifies the string in place and returns the character that was removed.
Example
my $string = "hello";
my $last_char = chop($string);
print "$string\n"; # Output: hell
print "$last_char\n"; # Output: o
In this example, we use chop to remove the last character ‘o’ from the string “hello”. The chop function modifies the string in place and returns the character that was removed, which is then printed to the screen.
chomp:
chomp, on the other hand, is used to remove the newline character(s) from the end of a string. It only removes the newline character(s) that appear at the end of the string, and leaves any other characters intact. Here’s an example:
my $string = "hello\n";
chomp($string);
print "$string"; # Output: hello
In this example, we use chomp to remove the newline character \n from the end of the string “hello\n”. The chomp function removes the newline character and modifies the string in place.
12. How can you retrieve only values from a hash in Perl?
To retrieve only the values from a hash in Perl, you can use the values function. The values function returns a list of all the values in the hash.
my %person = (
"name" => "John Smith",
"age" => 30,
"city" => "New York"
);
my @values = values %person; # Retrieve all values from hash
print "Values: @values\n";
13. How can you retrieve only keys from a hash in Perl?
To retrieve only the keys from a hash in Perl, you can use the keys function. The keys function returns a list of all the keys in the hash.
my %person = (
"name" => "John Smith",
"age" => 30,
"city" => "New York"
);
my @keys = keys %person; # Retrieve all keys from hash
print "Keys: @keys\n";
14. How can you check if a key exists or not in a hash in Perl?
To check if a key exists or not in a hash in Perl, you can use the exists function. The exists function returns a true value if the specified key exists in the hash and a false value otherwise.
my %person = (
"name" => "John Smith",
"age" => 30,
"city" => "New York"
);
if (exists $person{"name"}) {
print "Name exists in hash\n";
} else {
print "Name does not exist in hash\n";
}
15. How can you check the size of a hash in Perl?
In Perl, you can use the scalar function to get the size of a hash. When used with a hash variable, the scalar function returns the number of key-value pairs in the hash.
my %person = (
"name" => "John Smith",
"age" => 30,
"city" => "New York"
);
my $size = scalar %person; # Get size of hash
print "Size of hash: $size\n"; #output: Size of hash: 3
16. How can you delete keys from a hash in Perl?
In Perl, you can use the delete function to remove a key-value pair from a hash. The delete function takes the hash and the key as arguments and returns the value associated with the deleted key.
my %person = (
"name" => "John Smith",
"age" => 30,
"city" => "New York"
);
delete $person{"age"}; # Delete key "age"
print "After deleting 'age':\n";
while (my ($key, $value) = each %person) {
print "$key => $value\n";
}
Output:
After deleting 'age':
name => John Smith
city => New York
17. How can you delete the last character from all the elements in an array in Perl?
my @array = ("apple", "banana", "cherry");
chop(@array);
print "@array\n"; #output: appl banan cherr
In the above example deleted all the last letters.
18. How can you delete the last character from all the value in an hash in Perl?
my %hash = ( one => "one", two => "two", three => "three");
chop(%hash); #output: (one => "on", two => "tw", three => "thre");
In the above example deleted all the last letters.
19. How to create a reference array in Perl?
Using square brackets to enclose the array elements creates an array reference in Perl.
my $ref_array = [1,2,3,4,5];
20. How to create a reference hash in Perl?
Using square brackets to enclose the hash elements creates an array reference in Perl.
my $ref_hash = {one => "one", two => "two", three => "three"};
21. How to convert a dereferenced array into a reference array in Perl?
my @my_array = (1, 2, 3);
my $array_ref = \@my_array; # create a reference to @my_array
# dereference the array reference to get the original array
my @dereferenced_array = @{$array_ref};
# convert the dereferenced array back into a reference array
my $reference_array = \@dereferenced_array;
22. How to convert a dereferenced hash into a reference hash in Perl?
my %my_hash = ('key1' => 'value1', 'key2' => 'value2');
my $hash_ref = \%my_hash; # create a reference to %my_hash
# dereference the hash reference to get the original hash
my %dereferenced_hash = %{$hash_ref};
# convert the dereferenced hash back into a reference hash
my $reference_hash = \%dereferenced_hash;
23. How to access a value from a referenced array in Perl?
my $array_ref = [1, 2, 3]; # create a reference to an anonymous array
# access the second element of the array using the arrow operator
my $Value1 = $array_ref->[1];
print $Value1; # Output: 2
# access the second element of the array using the @{ } syntax
my $Value2 = @{$array_ref}[1];
print $Value2; # Output: 2
#access all values using loop
foreach(@{$array_ref}){
print "value = $_ \n";
}
24. How to access a value from a referenced hash in Perl?
my $hash_ref = {'key1' => 'value1', 'key2' => 'value2'}; # create a reference to an anonymous hash
# access the value associated with 'key2' using the arrow operator
my $value = $hash_ref->{'key2'};
print $value; # Output: value2
# access the value associated with 'key2' using the %{ } syntax
my $value1 = ${$hash_ref}{'key2'};
print $value1; # Output: value2
#access all values using loop
my %temp_hash = %{$hash_ref};
foreach(keys %temp_hash){
print "key = $_, value = $temp_hash{$_}\n";
}
25. What is the difference between “use” and “require” in Perl?
In Perl, both use and require are used to load external modules into your program. However, there are some differences between the two:
- `use` is a compile-time directive, while `require` is a runtime directive. This means that when you use `use` in your program, the module is loaded and processed at compile time, before the rest of the program is executed. On the other hand, when you use `require`, the module is loaded and processed at runtime, when the require statement is executed.
- `use` is automatically invoked at the beginning of the program, whereas `require` is used when you need to load a module at a specific point in your program.
- `use` automatically calls the `import` function of the module, which can be used to import specific functions or variables from the module into your program’s namespace. `require`, on the other hand, does not automatically call the `import` function and does not provide a way to import specific functions or variables from the module.
- If a module loaded using `use` fails to load, it will cause a fatal error and terminate the program. On the other hand, if a module loaded using `require` fails to load, it will issue a warning message, but the program will continue to run.
26. What is CPAN? Its uses?
CPAN stands for Comprehensive Perl Archive Network, and it is a vast repository of software modules and documentation for the Perl programming language. It was created in 1995 and is maintained by volunteers around the world.
The CPAN contains thousands of software modules that can be used to extend the functionality of Perl. These modules provide solutions to common programming problems, such as database connectivity, network programming, and text processing. Many of the modules in the CPAN are free and open-source, which makes them accessible to a wide range of developers.
you can install CPAN using the following command in your terminal or command prompt:
sudo yum install cpanminus
27. What purpose does each of the following serve: -w, strict, -T?
- “-w”: This is a command line option that turns on warnings in Perl. It instructs Perl to generate warning messages for potential issues in the code, such as using undefined variables or deprecated features. For example, if you have a variable that is not declared, Perl will generate a warning message. You can use this option by including it when you run your Perl script, like this:
perl -w myscript.pl
Alternatively, you can include the following line at the beginning of your Perl script to enable warnings:
use warnings;
- strict”: This is a pragma that enforces strict coding standards and helps catch common errors in Perl code. When you “use strict”, Perl will check for undeclared variables, use of barewords, and other potential errors. To use “use strict” in your code, simply include the following line at the beginning of your Perl script:
use strict;
use warnings;
- -T”: This is a command line option that enables taint mode in Perl. Taint mode is a security feature that ensures that all input from outside sources (such as user input or file input) is properly validated and sanitized before it is used in the program. Taint mode is particularly useful for web applications, where user input can be used in potentially dangerous ways. You can use this option by including it when you run your Perl script, like this:
perl -T myscript.pl
Alternatively, you can include the following line at the beginning of your Perl script to enable taint mode:
use taint;
28. Explain the use of do, require, use, import.
do
: do
loads a Perl script file, executes it, and returns the value of the last statement in the script. It is typically used for loading configuration files or scripts that generate code dynamically. Here is an example:
my $result = do 'config.pl';
require
: require
loads a Perl module file and returns a true value if the module is successfully loaded. It is typically used for loading libraries or modules that provide utility functions. If the module file is not found or fails to load, require
raises a fatal error and terminates the script. Here is an example:
require 'MyModule.pm';
use
: use
is similar to require
but provides additional features. It loads and imports a Perl module file, sets up any namespace or variable declarations defined by the module, and calls the module's import
function (if it has one). It is typically used for loading modules that provide reusable code or functionality. Here is an example:
use MyModule;
import
: import
is a method that is defined by a Perl module and is called automatically by use
. It is used to export symbols (e.g., functions, variables) from the module into the calling script's namespace. It can also be used to set up any module-specific options or configurations.
29. Use of our, my, and local?
our
: our
is used to declare package variables, which can be accessed from anywhere within the package, including from within subroutines. Package variables are declared with the our
keyword followed by the variable name.
my
: my
is used to declare lexical (block-scoped) variables, which are visible only within the block in which they are declared. A lexical variable is declared with the my
keyword followed by the variable name.
local
: local
is used to create a temporary dynamic scope for a package variable, which allows you to change the value of the variable within a specific block without affecting its value outside the block. The local
statement creates a temporary copy of the package variable with its current value and sets the variable to a new value within the block. When the block ends, the variable is restored to its previous value.
30. Use of the ref function
The ref()
function in Perl is used to determine the reference type of a given variable. It returns a string that describes the type of the reference.
Here is an example of how to use ref()
:
my $scalar_var = "Hello, world!";
my @array_var = (1, 2, 3);
my %hash_var = ('one' => 1, 'two' => 2, 'three' => 3);
my $scalar_ref = \$scalar_var;
my $array_ref = \@array_var;
my $hash_ref = \%hash_var;
print ref($scalar_ref) . "\n"; # prints "SCALAR"
print ref($array_ref) . "\n"; # prints "ARRAY"
print ref($hash_ref) . "\n"; # prints "HASH"
31. What are STDIN,STDOUT and STDERR?.
STDIN
is a filehandle that is used for input from the user or from another program. For example, if you want to read input from the user, you would use STDIN
like this:
print "Enter your name: ";
my $name = <STDIN>;
chomp $name;
print "Hello, $name!\n";
STDOUT
is a filehandle that is used for output to the console or to another program. For example, if you want to print output to the console, you would use STDOUT
like this:
print STDOUT "Hello, world!\n";
STDERR
is a filehandle that is used for error messages. For example, if you encounter an error while running a program, you can print an error message to STDERR
like this:
print STDERR "Error: Could not open file\n";
32. What does “use strict”, “use vars”, and “no vars” mean?
use strict: This pragma enforces strict coding standards and helps catch common errors in Perl code. When you “use strict”, Perl will check for undeclared variables, use of barewords (strings that are not enclosed in quotes), and other potential errors. To use “use strict” in your code, simply include the following line at the beginning of your Perl script:
use strict;
use vars: This pragma is used to declare global variables in your Perl code. It is similar to the “our” keyword, but works in older versions of Perl. To use “use vars”, simply include a list of variable names after the pragma, like this:
use vars qw($var1 $var2 @array1 %hash1);
no vars: This pragma is used to undo the effects of “use vars” or “our”. It can be used to remove variables from the global scope. To use “no vars”, simply include a list of variable names after the pragma, like this:
no vars qw($var1 $var2 @array1 %hash1);
33. @INC and %INC
@INC
is an array variable that contains a list of directories to be searched when Perl is looking for a module or library file. When you use the use
statement to load a module, Perl will search for the module file in each directory listed in @INC
until it finds the file or exhausts the list.
Here’s an example of how to use @INC
to add a new directory to the search path:
use lib '/path/to/my/lib'; # Add '/path/to/my/lib' to @INC
use MyModule; # Load 'MyModule' from '/path/to/my/lib'
%INC
is a hash variable that contains a list of modules and libraries that have been loaded by Perl during the current program execution. The keys of %INC
are the module names, and the values are the paths to the module files that were loaded.
Here’s an example of how to use %INC
to check if a module has been loaded:
use MyModule;
if (exists $INC{'MyModule.pm'}) {
print "MyModule has been loaded\n";
}
else {
print "MyModule has not been loaded\n";
}
34. How you can invoke a shell command?
In Perl, you can invoke a shell command by using the system
function or by using backticks or the qx
operator.
Here’s an example of how to use the system
function to invoke a shell command:
system("ls -l"); # Invoke the 'ls -l' shell command
In the above example, we use the system
function to invoke the ls -l
shell command. The system
function will pass the command to the shell to execute and return the exit status of the command.
You can also use backticks or the qx
operator to invoke a shell command and capture its output. Here's an example:
my $output = `ls -l`; # Invoke 'ls -l' and capture its output
print $output; # Print the output to the Terminal
In the above example, we use backticks or the qx
operator to invoke the ls -l
command and capture its output. The output is stored in the $output
variable, which we then print to the console using the print
function.
35. What is the exact difference between system() and exec().
The system()
function allows you to execute an external command and return its exit status. It forks a new process to run the command, waits for it to complete, and returns the exit status of the command. The system()
function takes a single argument, which is the command to execute.
Here’s an example of how to use system()
:
system('ls -l');
The exec()
function is used to replace the current process with a new process. It does not return to the original program after the external command has finished running. Instead, it loads and runs the external command in the current process, effectively replacing the Perl program with the command. The exec()
function takes a single argument, which is the command to execute.
Here’s an example of how to use exec()
:
exec('ls -l');
In the above example, the exec()
function replaces the Perl program with the ls -l
command. Any code following the exec()
call will not be executed.
So, the key difference between system()
and exec()
is that system()
forks a new process to execute the command, while exec()
replaces the current process with the new command. If you need to continue running Perl code after executing an external command, system()
is the better choice. If you want to completely replace the Perl program with the external command, use exec()
.
36. Error handling using eval
In Perl, the eval
function is used to catch exceptions and handle errors. The eval
function takes a block of code as an argument and attempts to execute it. If an exception occurs within the block of code, eval
catches the exception and returns the error message. Here's an example:
eval {
# Code that may throw an exception
die "Something went wrong";
};
if ($@) {
# Handle the error
print "Error: $@\n";
}
37. Explain eval EXPR and eval BLOCK.
eval EXPR
: This type of eval
statement takes an expression as an argument, which is evaluated as a string and executed as if it were a Perl code. The result of this evaluation is returned as a value. For example:
my $expr = "2 + 2";
my $result = eval $expr; # $result contains 4
In this example, the expression "2 + 2"
is evaluated as a string and then executed as Perl code using the eval
statement. The resulting value 4
is returned and stored in the $result
variable.
eval BLOCK
: This type of eval
statement takes a block of code as an argument, which is executed as if it were a separate Perl program. The result of the last evaluated expression in the block is returned as a value. For example:
my $result = eval {
my $a = 2;
my $b = 3;
$a + $b;
}; # $result contains 5
In this example, the block of code { ... }
containing the expressions $a = 2
, $b = 3
, and $a + $b
is executed as a separate Perl program using the eval
statement. The resulting value 5
is returned and stored in the $result
variable.
38. Explain qw,qq,qx (what’s its use, when to use).
qw
(quoted words): qw
is used to create a list of strings, separated by whitespace. The list is enclosed in parentheses and the strings are not quoted. For example, the following code creates a list of three strings:
my @words = qw(foo bar baz);
qq
(double quotes): qq
is used to create a double-quoted string, where variables are interpolated and escape sequences are interpreted. This is equivalent to using double quotes (""
) around a string literal. For example:
my $name = 'John';
my $greeting = qq(Hello, $name!\n);
This sets $greeting
to the string "Hello, John!\n", where the variable $name
is interpolated and the newline character is interpreted.
qx
(backticks): qx
is used to execute a command and capture its output as a string. This is equivalent to using backticks (````) around a command in shell. For example:
my $output = qx(ls -l);
This executes the ls -l
command and captures its output as a string in the $output
variable.
39. How to set Environment variables in Perl.
In Perl, environment variables can be set using the %ENV
hash. Each element in %ENV
represents an environment variable, where the key is the name of the variable and the value is its value.
To set an environment variable, you simply need to assign a value to the corresponding element in %ENV
. For example, the following code sets the MY_VAR
environment variable to the value "hello":
$ENV{MY_VAR} = 'hello';
40. Use of map and grep functions in Perl.
The map
function takes a code block and applies it to each element of a list or array, returning a new list or array that contains the results of the code block for each element. Here's an example that doubles each element of an array:
my @nums = (1, 2, 3, 4, 5);
my @doubled = map { $_ * 2 } @nums;
print "@doubled\n"; # prints "2 4 6 8 10"
The grep
function takes a code block and filters a list or array based on the elements that pass a truth test. It returns a new list or array that contains only the elements that pass the test. Here's an example that filters even numbers from an array:
my @nums = (1, 2, 3, 4, 5);
my @evens = grep { $_ % 2 == 0 } @nums;
print "@evens\n"; # prints "2 4"
41. What is the difference between die and exit in perl?
In Perl, both die
and exit
can be used to terminate a program, but they have different behaviors.
die
is typically used when there's a fatal error or an exception that the program can't recover from. It prints an error message to STDERR and terminates the program with a non-zero exit code, indicating that an error occurred. Here's an example:
die "Something went wrong: $!\n";
exit
, on the other hand, is typically used to terminate a program normally. It exits the program with a specified exit code (0 by default), indicating that the program completed successfully. Here's an example:
exit 1;
he main difference between die
and exit
is that die
is used to terminate a program due to an error condition, while exit
is used to terminate a program normally. Additionally, die
prints an error message to STDERR, while exit
does not.
42. How to find which method is being invoked or being called in Perl and in which method you are currently?
In Perl, you can use the caller
function to get information about the current call stack, including the name of the current subroutine (if any), the file name and line number of the caller, and the name of the package where the subroutine is defined. Here are a few examples:
To get the name of the current subroutine:
sub my_subroutine {
my $sub_name = (caller(0))[3];
print "Current subroutine is $sub_name\n";
}
In this example, caller(0)
returns an array containing information about the current call stack frame, including the name of the current subroutine (if any), which is stored in the fourth element of the array. The name of the current subroutine is then printed to STDOUT.
43. Explain the use of caller and wantarray function?
caller
is used to get information about the current execution frame. It takes a single argument, which specifies the depth of the stack frame to examine. For example, caller(0)
returns information about the current frame, while caller(1)
returns information about the calling frame, and so on. The function returns a list containing the following elements:
- Package name of the subroutine
- Filename of the file containing the subroutine
- Line number of the line in the file where the subroutine was called
- Subroutine name, or
undef
if none
wantarray
is used to determine the context of a function call. It returns true if the function was called in list context, false if it was called in scalar context, and undefined if it was called in void context. This allows you to write functions that behave differently depending on how they are called. For example:
sub my_function {
if (wantarray) {
return (1, 2, 3); # return a list
}
else {
return "1, 2, 3"; # return a string
}
}
my @list = my_function();
print "@list\n";
my $string = my_function();
print "$string\n";
44. How will you find line number, package and a file name in Perl?
To find the line number, package name, and file name in Perl, you can use the special variables __LINE__
, __PACKAGE__
, and __FILE__
, respectively.
Here’s an example:
#!/usr/bin/perl
use strict;
use warnings;
print "The current line number is ", __LINE__, "\n";
print "The current package name is ", __PACKAGE__, "\n";
print "The current file name is ", __FILE__, "\n";
When you run this script, you will see output that looks something like this:
The current line number is 5
The current package name is main
The current file name is /path/to/your/script.pl
Note that the __FILE__
variable returns the full path to the current file, so you may need to modify the output if you only want the file name without the path. You can use the basename
function from the File::Basename
module to do this:
use File::Basename;
my $filename = basename(__FILE__);
print "The current file name is $filename\n";
45. How to install a Perl Module from CPAN.
In the terminal enter cpanm along with perl module name.
cpanm Data::Dumper
46. Pass an array to subroutine and get t as array ref in sub.
#!/usr/bin/perl
use strict;
use warnings;
my @numbers = (1, 2, 3, 4, 5);
# Call the subroutine with an array reference
my $numbers_ref = print_numbers(\@numbers);
# Subroutine definition
sub print_numbers {
my $array_ref = shift; # Get the array reference from arguments
foreach my $number (@{$array_ref}) {
print "$number\n";
}
return $array_ref; # Return the array reference
}
47. Inbuilt special variable in Perl.
$!
- The system error message associated with the last system call that failed. For example, if you try to open a file that does not exist,$!
will contain a descriptive error message.$?
- The exit status of the last executed system command. This variable is set to 0 if the command was successful, or a non-zero value if there was an error.$_
- The default scalar variable used by many built-in functions if no argument is specified. For example, if you use thechomp
function without any arguments, it will remove the newline character from$_
.@ARGV
- An array containing the command-line arguments passed to the program.%ENV
- A hash containing the current environment variables.@INC
- An array containing the directories Perl searches for modules when using theuse
statement.@_
- An array containing the arguments passed to a subroutine.$0
- The name of the current program.__LINE__
- The current line number in the source code.__FILE__
- The name of the current file.
48. Piping in and piping out in Perl
In Perl, you can read from and write to external commands using pipes. The open
function can be used to create a pipe to an external command and read from or write to it like a file handle.
To pipe in, you can use the open
function to open a pipe to an external command for reading:
open(my $pipe, '-|', 'command args') or die "Can't open pipe: $!";
while (<$pipe>) {
# process input from the pipe
}
close($pipe);
In this example, the open
function opens a pipe to the external command "command args"
for reading. The -|
mode tells Perl to open the command in read mode. The die
function is called if the open
fails.
You can then read from the pipe like you would from a file handle using the <>
operator. In this case, while (<$pipe>)
reads input from the pipe until there is no more input. Finally, you need to close the pipe using close($pipe)
.
To pipe out, you can use the open
function to open a pipe to an external command for writing:
open(my $pipe, '|-', 'command args') or die "Can't open pipe: $!";
print $pipe "output to the pipe\n";
close($pipe);
In this example, the open
function opens a pipe to the external command "command args"
for writing. The |-
mode tells Perl to open the command in write mode. The die
function is called if the open
fails.
You can then write to the pipe like you would to a file handle using the print
function. In this case, print $pipe "output to the pipe\n"
writes output to the pipe. Finally, you need to close the pipe using close($pipe)
.
Note that you can use the same open
function to create a bidirectional pipe for reading and writing, by using the |-
mode and the -|
mode together. In this case, you can use the same pipe handle to read from and write to the external command.
49. How to implement stack and queue in Perl?
Stack:
# Initialize an empty stack
my @stack = ();
# Push an item onto the stack
push @stack, "item1";
# Pop an item off the stack
my $item = pop @stack;
In this example, @stack
is an array that represents the stack. To push an item onto the stack, you can use the push
function, and to pop an item off the stack, you can use the pop
function.
Queue:
# Initialize an empty queue
my @queue = ();
# Enqueue an item
push @queue, "item1";
# Dequeue an item
my $item = shift @queue;
In this example, @queue
is an array that represents the queue. To enqueue an item, you can use the push
function to add an item to the end of the array. To dequeue an item, you can use the shift
function to remove the first item from the array.
50. How to find the list of installed modules in Perl?
Using perl
:
- Open a terminal or command prompt.
- Type
perl -MExtUtils::Installed -e 'print join("\n", ExtUtils::Installed->new()->modules())'
and press Enter.
51. Use of BEGIN and END block.
BEGIN
blocks:
The BEGIN
block is executed as soon as it is compiled, before the rest of the code is executed. This allows you to perform setup tasks, such as loading modules or initializing variables, before the rest of the program runs. Here's an example:
BEGIN {
print "Starting program...\n";
# Perform setup tasks here
}
END
blocks:
The END
block is executed when the program or module is finished running, just before it exits. This allows you to perform cleanup tasks, such as closing files or releasing resources, before the program exits. Here's an example:
END {
# Perform cleanup tasks here
print "Exiting program...\n";
}
52. Simulate the behaviour of ‘use lib’ pragma using BEGIN block.
The use lib
pragma in Perl is used to add directories to the @INC
array, which is a list of directories that Perl searches for modules. You can simulate the behavior of use lib
using a BEGIN
block as follows:
BEGIN {
push @INC, "/path/to/directory";
}
In this example, the BEGIN
block adds the directory /path/to/directory
to the @INC
array using the push
function. This has the same effect as using the use lib "/path/to/directory";
statement.
File Handling in Perl
1. File Testing in Perl
-e file :
Returns true if the file exists.
-f file :
Returns true if the file exists and is a plain file (i.e., not a directory, symbolic link, etc.).
-d file :
Returns true if the file exists and is a directory.
-s file:
Returns the size of the file in bytes.
-T file:
Returns true if the file is a text file.
-B file:
Returns true if the file is a binary file.
-M file:
Returns the age of the file in days since the last modification.
-A file:
Returns the age of the file in days since the last access.
-C file:
Returns the age of the file in days since the inode was last changed.
my $filename = "example.txt";
if (-e $filename) {
print "File $filename exists\n";
}
if (-f $filename) {
print "File $filename is a plain file\n";
}
if (-T $filename) {
print "File $filename is a text file\n";
} else {
print "File $filename is a binary file\n";
}
my $size = -s $filename;
print "File $filename has size $size bytes\n";
2. Syntax for opening, appending, reading, writing files.
Opening a file for reading:
open(my $fh, "<", "filename.txt") or die "Can't open file: $!";
This code opens a file named filename.txt
for reading, and stores the file handle in the scalar variable $fh
. The or die
clause ensures that the program exits with an error message if the file cannot be opened.
Opening a file for writing:
open(my $fh, ">", "filename.txt") or die "Can't open file: $!";
This code opens a file named filename.txt
for writing, and stores the file handle in the scalar variable $fh
. The or die
clause ensures that the program exits with an error message if the file cannot be opened.
Opening a file for appending:
open(my $fh, ">>", "filename.txt") or die "Can't open file: $!";
This code opens a file named filename.txt
for appending, and stores the file handle in the scalar variable $fh
. The or die
clause ensures that the program exits with an error message if the file cannot be opened.
Reading from a file:
while(my $line = <$fh>) {
# Do something with $line
}
This code reads lines from the file handle $fh
and stores each line in the scalar variable $line
. The while
loop continues until there are no more lines to read from the file.
Writing to a file:
print $fh "Hello, world!\n";
This code writes the string “Hello, world!\n” to the file handle $fh
. The newline character \n
is included to ensure that the next line of output is written on a new line.
Appending to a file:
print $fh "More text to append\n";
This code appends the string “More text to append\n” to the end of the file handle $fh
. The newline character \n
is included to ensure that the appended text starts on a new line.
Closing a file:
close($fh)
This code closes the file handle $fh
, which ensures that any changes made to the file are saved and any system resources used by the file are freed.
3. How to assign File handle into an array instead of using while loop?
You can use the readline
function to read all the lines from a file into an array. Here's an example:
perlCopy code
open my $fh, "<", "filename.txt" or die "Can't open file: $!";
my @lines = readline $fh;
close $fh;
foreach my $line (@lines) {
# Do something with $line
}
In this example, the open
function is used to open the file "filename.txt"
for reading, and the file handle is stored in the scalar variable $fh
. The readline
function is then used to read all the lines from the file into the array @lines
. Finally, the close
function is used to close the file handle.
You can then iterate over the array @lines
to process each line of the file.
4. How to delete a file?
my $filename = "file_to_delete.txt";
unlink $filename or die "Can't delete file: $!";
In this example, the unlink
function is used to delete the file "file_to_delete.txt"
. If the file cannot be deleted, the die
function is called with an error message that includes the reason why the deletion failed.
Note that the unlink
function does not move the deleted file to the system's recycle bin or trash folder. Once you delete a file using unlink
, it's permanently deleted from the system.
5. How to copy or move a file?
use the File::Copy
module to copy or move files in Perl. Here are examples for both operations:
Copying a file
use File::Copy;
my $source_file = "source_file.txt";
my $destination_file = "destination_file.txt";
copy($source_file, $destination_file) or die "Copy failed: $!";
In this example, the copy
function is used to copy the file "source_file.txt"
to a new file named "destination_file.txt"
. If the copy operation fails, the die
function is called with an error message.
Moving a file
use File::Copy;
my $source_file = "source_file.txt";
my $destination_file = "destination_file.txt";
move($source_file, $destination_file) or die "Move failed: $!";
In this example, the move
function is used to move the file "source_file.txt"
to a new location and rename it to "destination_file.txt"
. If the move operation fails, the die
function is called with an error message.
Note that the move
function is used to both move and rename files. If you want to move a file to a new location without changing its name, you can simply use the rename
function:
rename($source_file, $destination_file) or die "Move failed: $!";
In this case, the rename
function is used to move the file "source_file.txt"
to the location specified by the $destination_file
variable. If the move operation fails, the die
function is called with an error message.
6. What are the various file permissions (flags) in Perl?
In Perl, file permissions are represented using octal numbers, with each digit representing a different set of permissions. The three digits represent permissions for the owner of the file, the group that the file belongs to, and everyone else.
The following are the various file permission flags in Perl:
- 0: No permissions
- 1: Execute permission
- 2: Write permission
- 3: Write and execute permissions
- 4: Read permission
- 5: Read and execute permissions
- 6: Read and write permissions
- 7: Read, write, and execute permissions
To set file permissions in Perl, you can use the chmod function. For example, to set read and write permissions for the owner of a file, you would use the following code:
chmod 0600, $filename;
In this example, “0600” represents the octal number for read and write permissions for the owner of the file.
7. Given a file, count the word occurrence (case insensitive).
=head
filename content
apple
mango
banana
mango
=cut
my $filename = 'filename.txt';
open my $fh, '<', $filename or die "Could not open file '$filename': $!";
my %count;
while (my $line = <$fh>) {
chomp $line;
$line =~ s/[^\w\s]//g; # Remove punctuation
$line = lc $line; # Convert to lowercase
my @words = split /\s+/, $line;
foreach my $word (@words) {
$count{$word}++;
}
}
close $fh;
foreach my $word (keys %count) {
print "$word: $count{$word}\n";
}
Output:
mango: 2
banana: 1
apple: 1
8. Displaying file contents using hash in Perl.
=head
filename content
apple
mango
banana
mango
=cut
my $filename = 'example.txt';
open my $fh, '<', $filename or die "Could not open file '$filename': $!";
my %content;
while (my $line = <$fh>) {
chomp $line;
$content{$.} = $line;
}
close $fh;
foreach my $line_num (sort {$a <=> $b} keys %content) {
print "$line_num: $content{$line_num}\n";
}
Output:
1: apple
2: mango
3: banana
4: mango