Perl interview questions 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?

Check out Perl Monks for discussion of the questions and related Perl interview issues. Check RegExpLib for regular expression samples.

This entry was posted in Unix/Linux, Web dev. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

20 Comments on Perl interview questions and answers

  1. Posted 4/4/2005 at 3:07 pm | Permalink

    There’s a whole thread on this set of questions at . If you’re an interviewer, be sure you read the comments and responses before you use these questions, as some of them will give you misleading answers or mistaken “failures”.

  2. Posted 4/4/2005 at 3:07 pm | Permalink

    Arrrgh. The URL got swallowed. That’s at http://www.perlmonks.org/index.pl?node_id=444520

  3. Dragonchild
    Posted 4/4/2005 at 4:11 pm | Permalink

    # Write a simple (common) regular expression to match an IP address, e-mail address, city-state-zipcode combination.

    This is a bad idea. An e-mail address is much harder than /^[\w\.]+\@\[\w\.]+\.[com|net|org]$/ - Check out RFC822 for more info. Same thing with city-state-zip. Rural addresses will blow you out of the water.

    Much better is something like:

    # Write a regular expression to match a phone number.

    Then, you watch how they write it. Of course, the regex is going to differ depending on what country you’re in. Important is whether or not they provide capturing, varying input lengths, and how they handle invalid input.

  4. Sunil Kartikey
    Posted 9/19/2005 at 4:48 am | Permalink

    local and my are different

    local does not work the same way as my. In particular, it doesn’t create private variables. Variables declared local remain global. Instead, Perl assigns a temporary value to the variable, and then restores the old value when the variable goes out of scope.

    Because variables declared as local are still global variables, there is another time where they are handy. Remember that my variables are private, and cannot be seen by subroutines. This is not true when they are declared local.

  5. Sunil Kartikey
    Posted 9/19/2005 at 4:58 am | Permalink

    use and require

    Perl offers several different ways to include code from one file into another. Here are the differences between the various inclusion commands:

    1) do $file is like eval `cat $file`, except that do
    1.1: searches @INC and updates %INC.
    1.2: gives an *unrelated* lexical scope to the eval’ed code.
    2) require $file is like do $file, except that require
    2.1: checks for redundant loading, skipping already loaded files.
    2.2: raises an exception on failure to find, compile, or execute $file.
    2.3: It may help, if you’re a C programmer, to think of require
    as being like #include
    3) require Module is like require “Module.pm”, except that require
    3.1: translates each “::” into your system’s directory separator.
    3.2: primes the parser to disambiguate class Module as an
    indirect object.
    4) use Module is like require Module, except that use
    4.1: loads the module at compile time, not run-time.
    4.2: imports symbols and semantics from that package to the current one

  6. Sunil Kartikey
    Posted 9/28/2006 at 7:59 am | Permalink

    When would you not use Perl for a project?

    When your manager forbids it–but do consider replacing them :-).

    Actually, one good reason is when you already have an existing application written in another language that’s all done (and done well), or you have an application language specifically designed for a certain task (e.g. prolog, make).

    For various reasons, Perl is probably not well-suited for real-time embedded systems, low-level operating systems development work like device drivers or context-switching code, complex multi-threaded shared-memory applications, or extremely large applications. You’ll notice that perl is not itself written in Perl.

    The new, native-code compiler for Perl may eventually reduce the limitations given in the previous statement to some degree, but understand that Perl remains fundamentally a dynamically typed language, not a statically typed one. You certainly won’t be chastised if you don’t trust nuclear-plant or brain-surgery monitoring code to it. And Larry will sleep easier, too–Wall Street programs not withstanding. :-)

  7. Abhishek Shrivastava
    Posted 11/20/2006 at 1:54 am | Permalink

    Regular Expression of IP Address :

    (\d|\d\d|1\d\d|2[0-4]\d|25[0-5]).

    :-)

  8. Abhishek Shrivastava
    Posted 11/20/2006 at 2:03 am | Permalink

    Answer 3:
    These are the variables begin with “$”, “@” or “%” in Perl.

  9. mohit thakkar
    Posted 12/22/2006 at 12:59 am | Permalink

    I want to ask question that what is the differance while using package in JAVA and in PERL and also what do we mean by %main:: and %:: are same??

    hope you give me that answers very soon

    thanks

  10. Miriam Smith
    Posted 2/13/2007 at 12:56 pm | Permalink

    What arguments do you frequently use for the Perl interpreter and what do they mean?
    perl [ -sTuU ] [ -hv ] [ -V[:configvar] ] [ -cw ] [ -d[:debugger] ] [ -D[number/list] ] [ -pna ] [ -Fpattern ] [ -l[octal] ] [ -0[octal] ] [ -Idir ] [ -m[-]module ] [ -M[-]‘module…’ ] [ -P ] [ -S ] [ -x[dir] ] [ -i[extension] ] [ -e 'command' ] [ -- ] [ programfile ] [ argument ]
    What does the command ‘use strict’ do and why should you use it?
    A command like use strict is called a pragma. Pragmas are instructions to the Perl interpreter to do something special when it runs your program. use strict does two things that make it harder to write bad software: It makes you declare all your variables (“strict vars”), and it makes it harder for Perl to mistake your intentions when you are using subs (“strict subs”).
    What do the symbols $ @ and % mean when prefixing a variable?
    $varialble
    @array
    %hash
    What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?
    modules
    What are the characteristics of a project that is well suited to Perl?
    For writing exploits, testing products and apps, identifying new Web-based vulnerabilities, and creating complex regular-expression engines.
    Why do you program in Perl? Why not
    Explain the difference between my and local.
    The variables declared with my() are visible only within the scope of the block which names them. They are not visible outside of this block, not even in routines or blocks that it calls. local() variables, on the other hand, are visible to routines that are called from the block where they are declared. Neither is visible after the end (the final closing curly brace) of the block at all.
    Explain the difference between use and require.
    require() reads a file containing Perl code and compiles it. Before attempting to load the file it looks up the argument in %INC to see whether it has already been loaded. If it has, require() just returns without doing a thing. Otherwise an attempt will be made to load and compile the file.
    require() has to find the file it has to load. If the argument is a full path to the file, it just tries to read it. For example:
    require “/home/httpd/perl/mylibs.pl”;
    If the path is relative, require() will attempt to search for the file in all the directories listed in @INC. For example:
    require “mylibs.pl”;
    If there is more than one occurrence of the file with the same name in the directories listed in @INC the first occurrence will be used.
    The file must return TRUE as the last statement to indicate successful execution of any initialization code. Since you never know what changes the file will go through in the future, you cannot be sure that the last statement will always return TRUE. That’s why the suggestion is to put “1;” at the end of file.
    Although you should use the real filename for most files, if the file is a module, you may use the following convention instead:
    require My::Module;
    This is equal to:
    require “My/Module.pm”;
    If require() fails to load the file, either because it couldn’t find the file in question or the code failed to compile, or it didn’t return TRUE, then the program would die(). To prevent this the require() statement can be enclosed into an eval() exception-handling block, as in this example:
    require.pl
    ———-
    #!/usr/bin/perl -w

    eval { require “/file/that/does/not/exists”};
    if ($@) {
    print “Failed to load, because : $@”
    }
    print “\nHello\n”;
    When we execute the program:
    % ./require.pl

    Failed to load, because : Can’t locate /file/that/does/not/exists in
    @INC (@INC contains: /usr/lib/perl5/5.00503/i386-linux
    /usr/lib/perl5/5.00503 /usr/lib/perl5/site_perl/5.005/i386-linux
    /usr/lib/perl5/site_perl/5.005 .) at require.pl line 3.

    Hello
    We see that the program didn’t die(), because Hello was printed. This trick is useful when you want to check whether a user has some module installed, but if she hasn’t it’s not critical, perhaps the program can run without this module with reduced functionality.
    If we remove the eval() part and try again:
    require.pl
    ———-
    #!/usr/bin/perl -w

    require “/file/that/does/not/exists”;
    print “\nHello\n”;
    % ./require1.pl

    Can’t locate /file/that/does/not/exists in @INC (@INC contains:
    /usr/lib/perl5/5.00503/i386-linux /usr/lib/perl5/5.00503
    /usr/lib/perl5/site_perl/5.005/i386-linux
    /usr/lib/perl5/site_perl/5.005 .) at require1.pl line 3.
    The program just die()s in the last example, which is what you want in most cases.
    use(), just like require(), loads and compiles files containing Perl code, but it works with modules only and is executed at compile time.
    The only way to pass a module to load is by its module name and not its filename. If the module is located in MyCode.pm, the correct way to use() it is:
    use MyCode
    and not:
    use “MyCode.pm”
    use() translates the passed argument into a file name replacing :: with the operating system’s path separator (normally /) and appending .pm at the end. So My::Module becomes My/Module.pm.
    use() is exactly equivalent to:
    BEGIN { require Module; Module->import(LIST); }
    Internally it calls require() to do the loading and compilation chores. When require() finishes its job, import() is called unless () is the second argument. The following pairs are equivalent:
    use MyModule;
    BEGIN {require MyModule; MyModule->import; }

    use MyModule qw(foo bar);
    BEGIN {require MyModule; MyModule->import(”foo”,”bar”); }

    use MyModule ();
    BEGIN {require MyModule; }
    The first pair exports the default tags. This happens if the module sets @EXPORT to a list of tags to be exported by default. The module’s manpage normally describes what tags are exported by default.
    The second pair exports only the tags passed as arguments.
    The third pair describes the case where the caller does not want any symbols to be imported.
    import() is not a builtin function, it’s just an ordinary static method call into the “MyModule” package to tell the module to import the list of features back into the current package. See the Exporter manpage for more information.
    When you write your own modules, always remember that it’s better to use @EXPORT_OK instead of @EXPORT, since the former doesn’t export symbols unless it was asked to. Exports pollute the namespace of the module user. Also avoid short or common symbol names to reduce the risk of name clashes.
    When functions and variables aren’t exported you can still access them using their full names, like $My::Module::bar or $My::Module::foo(). By convention you can use a leading underscore on names to informally indicate that they are internal and not for public use.
    There’s a corresponding “no” command that un-imports symbols imported by use, i.e., it calls Module->unimport(LIST) instead of import().

    What’s your favorite module and why? IO::Socket
    Where do you go for Perl help?Google. CPAN.
    When would you not use Perl for a project? For longer term projects

  11. Balaji
    Posted 5/15/2007 at 5:07 am | Permalink

    3. What do the symbols $ @ and % mean when prefixing a variable?

    Answer:
    $ is used for a normal variable.
    @ is for an index array.
    % is for associative array.

  12. novandria
    Posted 6/12/2007 at 3:50 pm | Permalink

    What do the symbols $ @ and % mean when prefixing a variable?

    $ Scalar
    @ Array
    % Hash

  13. Shail
    Posted 6/22/2007 at 5:51 am | Permalink

    Q -> How do you open a file for writing?

    open (”FH”, “>filename.dat”) || die “Can’t create the file\n”;

    Later use FH to perform all file realted operation.

    Cheers!
    Shail

  14. Shail
    Posted 6/22/2007 at 5:58 am | Permalink

    Q -> What does the command ‘use strict’ do and why should you use it?

    As we know that in PERL there is no need to define the variable prior to use. Sometime while dealing with a bulky code spelling mistake can cause a big trouble. For example

    ——————-

    #!/usr/bin/perl

    $input = 5;
    print $ipnut,”\n”;

    ——————-

    this code will get executed without any error but the result would be something other than 5.

    To avoid such issues we genraly use:

    ——————-

    #/usr/bin/perl

    use strict;

    my $input =5;
    print $ipnut,”\n”;

    ——————-

    This would throw an error at the time of execution. As ‘$ipnut’ is not defined anywhere in the code.

    Cheers!
    Shail

  15. Steve Coleman
    Posted 7/7/2007 at 8:08 am | Permalink

    I’m running a PERL script on Linux ES 4 with ActiveState 5.8.8.820 (just upgraded). I have a perl script that builds command line functions for Oracle Application Server DMSTOOL commands. Basically from info provide I construct the DMSTOOL command, execute it, and parse the output. Everything works fine on Windows but when I ported the script to Linux, it ceased to function. I converted everthing that needed to be converted. The only thing left is a string concatenation that won’t concatenate properly. I’m attempting to build a command, $dmscommand, by concatenating ‘dmstool -table’ . tablename . ‘ -count 1′….when perl executes this…it takes the ‘ -count 1 and places it as the begining of $dmscommand overlaying the ‘dmstool -table tablename’ portion….I tried JOIN..same thing…what is it about ‘ -count 1′?????? Any guidance would be most apprecidate.

  16. Mahesh R
    Posted 10/25/2007 at 1:15 pm | Permalink

    Where do you go for Perl help?

    PerlDoc is a very good documentation for perl. Apart from perl doc you can check in “search.cpan.org” website for the specific modules details which you are using.
    There are some good books from Orielly as well.

  17. Simple
    Posted 10/25/2007 at 1:18 pm | Permalink

    Name an instance where you used a CPAN module?

    a. XMLParser: Parsing XML files.

  18. Posted 7/30/2008 at 12:37 pm | Permalink

    Q3. What do the symbols $ @ and % mean when prefixing a variable?

    $ -> is used to denote a scalar variable

    @ -> is used to denote an variable of type array

    % -> is used to denote a variable of type Hash

  19. Posted 7/30/2008 at 2:29 pm | Permalink

    Q-10. What is a hash?
    Hash is primitive data structure in Perl as in all other languages.
    A hash is a key => value pair mapping. Given a unique key you can store an associated value for the key.

    The time complexity for read, insert and deletion are O(1).

  20. Posted 7/30/2008 at 2:40 pm | Permalink

    Q What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?

    Perl can be used as a fully Object Oriented language with Packages, Classes and modules.

    This brings more modularity to the code

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*