Showing posts with label perl faqs. Show all posts
Showing posts with label perl faqs. Show all posts

Perl Interview Question and answers

 Perl Interview Question and answers
  1. What arguments do you frequently use for the Perl interpreter and what do they mean?
  2. What does the command ‘use strict’ do and why should you use it?
  3. What do the symbols $ @ and % mean when prefixing a variable?
  4. What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?
  5. What are the characteristics of a project that is well suited to Perl?
  6. Why do you program in Perl?
  7. Explain the difference between my and local.
  8. Explain the difference between use and require.
  9. What’s your favorite module and why?
  10. What is a hash?
  11. Write a simple (common) regular expression to match an IP address, e-mail address, city-state-zipcode combination.
  12. What purpose does each of the following serve: -w, strict, -T ?
  13. What is the difference between for & foreach, exec & system?
  14. Where do you go for Perl help?
  15. Name an instance where you used a CPAN module.
  16. How do you open a file for writing?
  17. How would you replace a char in string and how do you store the number of replacements?
  18. When would you not use Perl for a project?

Perl interview faqs,perl interview question and answers

Perl interview question and answers
When would `local $_' in a function ruin your day?
When your caller was in the middle for a while(m//g) loop
The /g state on a global variable is not protected by running local on it. That'll teach you to stop using locals. Too bad $_ can't be the target of a my() -- yet.

What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }' ?
Their destructors are called when that interpreter thread shuts down.
When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code.

Assume that $ref refers to a scalar, an array, a hash or to some nested data structure. Explain the following statements:
$$ref; # returns a scalar
$$ref[0]; # returns the first element of that array
$ref- > [0]; # returns the first element of that array
@$ref; # returns the contents of that array, or number of elements, in scalar context
$&$ref; # returns the last index in that array
$ref- > [0][5]; # returns the sixth element in the first row
@{$ref- > {key}} # returns the contents of the array that is the value of the key "key"


How do you match one letter in the current locale?
/[^\W_\d]/
We don't have full POSIX regexps, so you can't get at the isalpha() macro save indirectly. You ask for one byte which is neither a non-alphanumunder, nor an under, nor a numeric. That leaves just the alphas, which is what you want.

How do I print the entire contents of an array with Perl?
To answer this question, we first need a sample array. Let's assume that you have an array that contains the name of baseball teams, like this:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
If you just want to print the array with the array members separated by blank spaces, you can just print the array like this:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
print "@teams\n";
But that's not usually the case. More often, you want each element printed on a separate line. To achieve this, you can use this code:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
foreach (@teams) {
print "$_\n";
}

Perl uses single or double quotes to surround a zero or more characters. Are the single(' ') or double quotes (" ") identical?
They are not identical. There are several differences between using single quotes and double quotes for strings.
1. The double-quoted string will perform variable interpolation on its contents. That is, any variable references inside the quotes will be replaced by the actual values.
2. The single-quoted string will print just like it is. It doesn't care the dollar signs.
3. The double-quoted string can contain the escape characters like newline, tab, carraige return, etc.
4. The single-quoted string can contain the escape sequences, like single quote, backward slash, etc.

How many ways can we express string in Perl?
Many. For example 'this is a string' can be expressed in:
"this is a string"
qq/this is a string like double-quoted string/
qq^this is a string like double-quoted string^
q/this is a string/
q&this is a string&
q(this is a string)

How do you give functions private variables that retain their values between calls?
Create a scope surrounding that sub that contains lexicals.
Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus:
{ my $i = 0; sub next_i { $i++ } sub last_i { --$i } }
creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.

How do I read command-line arguments with Perl?

How do I read command-line arguments with Perl?
With Perl, command-line arguments are stored in the array named @ARGV.
$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.
Here's a simple program:
#!/usr/bin/perl
$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";
foreach $argnum (0 .. $#ARGV) {
print "$ARGV[$argnum]\n";
}

How to concatenate strings with Perl?

How to concatenate strings with Perl?
Method #1 - using Perl's dot operator:
$name = 'checkbook';
$filename = "/tmp/" . $name . ".tmp";

Method #2 - using Perl's join function
$name = "checkbook";
$filename = join "", "/tmp/", $name, ".tmp";

Method #3 - usual way of concatenating strings
$filename = "/tmp/${name}.tmp";

What is the easiest way to download the contents of a URL with Perl?

What is the easiest way to download the contents of a URL with Perl?

Once you have the libwww-perl library, LWP.pm installed, the code is this:
#!/usr/bin/perl
use LWP::Simple;
$url = get 'http://www.websitename.com/';

How do I replace every character in a file with a comma in perl?-Perl faqs

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

What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash in perl?

What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?
5
length() is a built-in prototyped as sub length($), and a scalar prototype silently changes aggregates into radically different forms. The scalar sense of a hash is false (0) if it's empty, otherwise it's a string representing the fullness of the buckets, like "18/32" or "39/64". The length of that string is likely to be 5. Likewise, `length(@a)' would be 2 if there were 37 elements in @a.

How to dereference a reference in perl-Perl faqs

How to dereference a reference in perl-Perl faqs
There are a number of ways to dereference a reference.
Using two dollar signs to dereference a scalar.
$original = $$strref;
Using @ sign to dereference an array.
@list = @$arrayref;
Similar for hashes.

Does Perl have reference type?

Does Perl have reference type?
Yes. Perl can make a scalar or hash type reference by using backslash operator.
For example
$str = "here we go"; # a scalar variable
$strref = \$str; # a reference to a scalar

@array = (1..10); # an array
$arrayref = \@array; # a reference to an array
Note that the reference itself is a scalar.

What's the difference between /^Foo/s and /^Foo/ in perl -Perl faqs

What's the difference between /^Foo/s and /^Foo/ in perl -Perl faqs
The second would match Foo other than at the start of the record if $* were set.
The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only at the ends of the string and not at ends of line as well -- just as they would if $* weren't set at all.

What value is returned by a lone `return;' statement in perl-Perl Faqs

What value is returned by a lone `return;' statement in perl-Perl Faqs
The undefined value in scalar context, and the empty list value () in list context.
This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.

How to find the length of an array in perl?-Perl interview

How to find the length of an array in perl?-Perl interview

$@array

How to read file into hash array in perl?-Perl interview

How to read file into hash array in perl?-Perl interview
open (IN, ""(filename in quotes))
or die "Couldn't open file for processing: $!";
while () {
chomp;
$hash_table{$_} = 0;
}
close IN;

print "$_ = $hash_table{$_}\n" foreach keys %hash_table;

How do I sort a hash by the hash value in perl?

How do I sort a hash by the hash value in perl?
Here's a program that prints the contents
of the grades hash, sorted numerically by the hash value:

#!/usr/bin/perl -w
# Help sort a hash by the hash 'value', not the 'key'.
to highest).
sub hashValueAscendingNum {
$grades{$a} <=> $grades{$b};
}

# Help sort a hash by the hash 'value', not the 'key'.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
$grades{$b} <=> $grades{$a};
}

%grades = (
student1 => 90,
student2 => 75,
student3 => 96,
student4 => 55,
student5 => 76,
);
print "\n\tGRADES IN ASCENDING NUMERIC ORDER:\n";
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print "\t\t$grades{$key} \t\t $key\n";
}
print "\n\tGRADES IN DESCENDING NUMERIC ORDER:\n";
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print "\t\t$grades{$key} \t\t $key\n";
}

What does read() return at end of file in perl?-Perl interview

What does read() return at end of file in perl?
0
A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().

Why does Perl not have overloaded functions? -Perl interview

Why does Perl not have overloaded functions?
Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they're references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can't do this, you simply must resort to overloading of functions.