Q26. What is the difference in Exec, System and ` `
1.> $var = system("command");
2.> $var = exec("command");
3.> $var = `command`;
A26.
1. System() returns the output on console and status to variable and control moves to next statement.
2. Exec() returns the output on console and Exit from the program.
3. ` ` returns the output to variable and control moves to next statement.
Explanation:
The exec function* replaces the current process with the one specified in the arguments, so exec("bash", "-l") would replace the perl process with bash login shell running interactively. This is most often not what you want to do. You want to run an external program and wait for it to finish. To do this you would need to fork the current process into two processes (parent and child) and replace the child process with an exec call to the external program while the parent process waits for the child process to complete. This is what the systemfunction** does. It is implemented in terms of a fork***, an exec, and a waitpid****. Due to the way fork works the file handles of the parent are inherited by the child, so STDOUT and STDERR in the process created by system are the same as in the Perl program. This is why output shows up when you use system or exec.
The qx// operator***** (also known as ``) is very different. It is most likely implemented via the popen****** function from SUSv2*******.
It captures the STDOUT (but not the STDERR) of an external program and returns it as a list of lines (in list context) or as string (in scalar context).
Other options for running (and capturing output/providing input)include the open function******** (STDOUT or STDIN only),
IPC::Open2********* (STDIN and STDOUT), and IPC::Open3********** (STDIN, STDOUT, and STDERR).
If you are not writing a quick and dirty program the open function is preferable to the qx// operator because you have more control and the
output data shows up as soon as possible (rather than at the end of the external program's run):
open my $output, "-|", "program_to_execute", "argument 1", "argument 2"
or die "could not run program: $!";
while (my $line = <$output>) {
#do something with a line printed by program_to_execute
#$line shows up here as soon as it is flushed
}
IPC::Open2 and IPC::Open3 provide even more control, and are useful
for puppet stringing other programs.
Q27.replace a char in string and how do you store the number of replacements?
A27.
my $mainstring = "APerlAReplAFunction";
my $count = ($mainstring =~ tr/A//);
print "There are $count As in the given string\n";
print $mainstring;
Q28. There are some duplicate entries in an array and you want to remove them. How would you do that? (*****)
A28.If duplicates need to be removed, the best way is to use a hash.
sub uniqueentr {
return keys %{{ map { $_ => 1 } @_ }};
}
@array1 = ("tea","coffee","tea","cola”,"coffee");
print join(" ", @array1), "\n";
print join(" ", uniqueentr(@array1)), "\n";
------------------OR-----------------
my @array1 = ("tea","coffee","tea","cola","coffee");
my %hash;
foreach (@array1)
{
$hash{$_}=1;
}
print join(" ", keys %hash);
Q29.What is eval
A29. used for debugging, even if program die within block of eval function, program outside eval block will get execute
my $a=3;
my $b=1;
$answer = $a / $b;
eval {
die if($a);
};
warn $@ if $@;
print "$@ ". $. ." \n ". __LINE__ ."uiuhhih $answer";
The eval function provides a very simple way of checking certain events without affecting the overall execution of your script. In essence the eval function just initiates a new instance of the Perl interpreter in order to evaluate a particular string or block. It s used in all sorts of places within Perl including in the debugger where it allows you to execute those arbitrary statements but it can also be employed as a debugging tool. Because eval evaluates a Perl statement or block within its own interpreter we can use it in situations that might otherwise cause the Perl interpreter to fail. This process works because an embedded eval block reports any errors raised by a call to die through the $@ variable. In fact any exit is reported through eval to the $@ special variable. We can demonstrate this with a simple eval block used to test the existence of a particular module:
eval
{
require Net::FTP;
}
print Error: Module failed to load ($@) if $@;
This outputs the following:
$ perl eval.pl
Failed to load Net::FTP: Can't locate Net/LICK.pm in @INC (@INC contains:
/usr/local/lib/perl5/5.6.0/i686-linux /usr/local/lib/perl5/5.6.0
/usr/local/lib/perl5/site_perl/5.6.0/i686-linux
/usr/local/lib/perl5/site_perl/5.6.0 /usr/local/lib/perl5/site_perl .) at
eval.pl line 1.
Q30. What is CONSTANT variables in perl
A30. Like C, perl replace the variable defined as CONSTANT with their values at compile time and you cannot modify it during run time. This can be done using hard reference also. But using constant pragama is more friendly.
use constant FOO => "BAR";
print "The value of FOO is ". FOO . "\n";
Note: for this need to install module "constant" and Constant should not be in quote " "
Q31. Write code to validate an IP address
A31.We recently had a need on an intranet site to validate the format of IP addresses being entered. Remember that IP addresses must have 4 parts, separated by periods, and that each part must be in the range of 0 to 255. Also note that "000" for a part would be valid, as would "0".
So, the first thing we do is make sure there are 4 groups of numbers (anywhere from 1 to 3 digits) separated by periods. Use a regular expression to do that. If the string passes that test, then split up the string into its 4 parts. The first part cannot be the number zero, so a check is done for that. None of
the parts can be greater than 255, so just use a little loop to check the value of each part to make sure it is less than or equal to 255. If everything passes, return true, otherwise return false.
sub is_ipv4 {
my $self = shift if ref($_[0]);
my $value = shift;
return unless defined($value);
my(@octets) = $value =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
return unless (@octets == 4);
foreach (@octets) {
#return unless ($_ >= 0 && $_ <= 255);
return unless ($_ >= 0 && $_ <= 255 && $_ !~ /^0\d{1,2}$/);
}
return join('.', @octets);
}
---------------------OR--------------------------
my $str= "255.255.255.24";
if($str=~/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) # validate it has 4 groups each having 1-3 digits
{
@ret= split(/\./,$str);
if( ($ret[0]>0 and $ret[0]<=255) and ($ret[1]>=0 and $ret[1]<=255) and
($ret[2]>=0 and $ret[2]<=255) and ($ret[3]>=0 and $ret[3]<=255) )
{
print "yes";
}
}
Note : You can directly use package Data::Validate::IP
Link : http://cpansearch.perl.org/src/NEELY/Data-Validate-IP-0.14/lib/Data/Validate/IP.pm
http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C87006CC664
Q32.why is the 'return 1;' necessary at the end of perl modules
A32. Typically, a module contains a bunch of subroutine definitions. A module may also contain code which is not part of a subroutine. This code is executed at the time the module is loaded, so it can be used to initialize the module. For example, the module might open a datatbase connection or initialize some time at the time it is loaded.
Such code might be successful, or it might fail. Perl allows the module to indicate the result by returning a true or false value back to its caller. If the value is false, Perl aborts the compilation with an error message.
Unfortunately, the default return value is *false*, so a module which just defines a bunch of subroutines, and which has no initialization
code, accidentally returns a false value back to the caller, and Perl aborts. So we insert "1;" at the end to suppress this misbehavior.
Link: http://lists.netisland.net/archives/phlpm/phlpm-2001/msg00426.html
Q33.Can we ordered a hash?
A33.
Tie::Hash::Indexed - Ordered hashes for Perl
use Tie::Hash::Indexed;
tie my %hash, 'Tie::Hash::Indexed';
%hash = ( I => 1, n => 2, d => 3, e => 4 );
$hash{x} = 5;
print keys %hash, "\n"; # prints 'Index'
print values %hash, "\n"; # prints '12345'
Link: http://search.cpan.org/~mhx/Tie-Hash-Indexed-0.05/lib/Tie/Hash/Indexed.pm
Q34. What is the difference between fork and thread
A34.
1. fork()
Note that this only works on UNIX-like systems (like Linux). fork() is a library function which, when
called, copies the entire process (including all variables) into a second process. Anything after the
fork() call is therefore executed twice. fork() returns 0 to new process(the child) and the PID of the
child to the calling process (the parent). Note that this is different from threads, because two
separate processes are run. This approach is sometimes used in web servers, so that a new process ifs
forked for every client. This is easy to program, but inefficient, as you've got a new process for
every client.Interaction between two of those processes is really hard you'd have to use an
intermediate file or something).
2. Threads
pointer to the function you want the thread to execute Thread is more effective in memory management
because it uses the samememory block of parent process instead of creating new memory block to run
new process. But in *NIX environment, it is not as easy as MS-Win environment to use thread.
External Links
http://www.careerride.com/perl-interview-questions.aspx#perl29
http://www.techinterviews.com/perl-interview-questions-and-answers