Thursday, June 28, 2012

Perl Interview Questions Part 5

Q:How can you find the length of an array?
 A:$@array

Q:What does `$result = f() .. g()’ really return?
A:False providing f() returns false, after which it returns true until g() returns true, and then starts the cycle again.This is scalar not list context, so we have the bistable flip-flop range operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()’. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will certainly be evaluated on the same record. If you don’t want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this:
$bingo = ( a() .. b() ) … ( c() .. d() );

Q:Why does Perl dont have overloaded functions?
A:Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is actually 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 /^+$/ otherwise. In languages like C++ where you can not do this, you simply must resort to overloading of functions.

Q:What does read() return at end of file?
A:A defined (but false) 0 value may be the proper indication of the end of file for read() and sysread().

Q:How do I do < fill-in-the-blank > for each element in a hash?
A:Here’s a simple technique to process each element in a hash:
#!/usr/bin/perl -w
%days = (
‘Sun’ =>’Sunday’,
‘Mon’ => ‘Monday’,
‘Tue’ => ‘Tuesday’,
‘Wed’ => ‘Wednesday’,
‘Thu’ => ‘Thursday’,
‘Fri’ => ‘Friday’,
‘Sat’ => ‘Saturday’ );
foreach $key (sort keys %days)
print “The long name for $key is $days$key.”;

Q:What value is returned by a lone `return;’ statement?
A
: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.


No comments:

Post a Comment