Home  |   Guest Book |    Technical Page |    Personal Page   

Perl Section
 
About Me
Who is a Good QA
Latest News
Testing Concepts
Automation Tools
Agile Development
UNIX Basics
Perl Scripting
Python Scripting
MySQL
Technology
Repository
Imp. Commands
My Resume

Perl KNOWLEDGE Questions


1. What are Perl anonymous subroutines and when they should be used instead of named one?
ANSWER:


 •You can store anonymous subs in arrays, hashes and scalars.
 •You can build them at runtime
 •You can pass them as arguments to other functions.
 •You get to keep variables in the surrounding scope.

 sub outer{
        my $a = 123;
        sub inner {
                print $a, "\n";
         }
         # At this point, $a is 123, so this call should always print 123, right?
         inner();
         $a = 456;
  }


outer(); # prints 123
outer(); # prints 456!
Surprise!But change "inner" from a named subroutine to a reference to an anonymous subroutine and it works is a much less surprising manner:

sub outer{
       my $a = 123;
       my $inner = sub {
              print $a, "\n";
       };
# At this point, $a is 123, and since the anonymous subrotine whose reference is stored in $inner closes over $a in the "expected" way...
       $inner->();
       $a = 456;
}

# ...we see the "expected" results
outer(); # prints 123
outer(); # prints 123




2. What are closures, define them with example.
ANSWER:

CLOSURE are Perl subroutine which can return a reference to a subroutine . This is really no different from any other ways of passing subroutine references around, except for a somewhat hidden feature involving anonymous subroutines and lexical ( my ) variables. Consider

 $greeting = "hello world";
 $rs = sub { 
       print $greeting;
 };
 &$rs(); #prints "hello world"

In this example, the anonymous subroutine makes use of the global variable $greeting . No surprises here, right? Now, let's modify this innocuous example slightly:


 sub generate_greeting { 
       my($greeting) = "hello world"; 
       return sub {print $greeting};
 }
 $rs = generate_greeting();
 &$rs(); # Prints "hello world"


The generate_greeting subroutine returns the reference to an anonymous subroutine, which in turn prints $greeting . The curious thing is that $greeting is a my variable that belongs to generate_greeting . Once generate_greeting finishes executing, you would expect all its local variables to be destroyed. But when you invoke the anonymous subroutine later on, using &$rs() , it manages to still print $greeting .

3. Different kind of Perl Modules and there usage .
ANSWER:


    1. strict;                               # Force strict compilation
    2. warnings;                       # Report and die on any compile/runtime warnings.
    3. Cwd;                                # Get pathname of current working directory
    4. Term::ANSIColor;          # Give color on cmd prompt
    5. Benchmark;                    # get time taken by the commands
    6. Expect;                             # get text from the command line and match
    7. IO::Tty;                              # input / output on terminal
    8. CGI;                                  # Networking constants and support functions
    9. File::Find;                        # Traverse a directory trees
   10. File::Basename;          # To get the file basename
   11. Tie::IxHash;                   # Base class definitions for tied hashes
   12. Switch                            # use switch command
   13. Net::FTP;                        # To FTP to other machine
   14. Getopt::Long;                 # Read command line options.
   15. Socket;                           # Connect other program on socket.
   16. XML::Simple                  # provides an easy API to read and write XML
   17. MIME::Lite                      # For email communication
   18. Data::Dumper               # Stringified perl data structures, suitable for both printing and eval
   19. DBD                                # DataBase Drivers
   20. DBI                                  # DataBase Interface, use DBI to connect to database
   21. DynaLoader                  # Dynamically load C libraries into Perl code
   22. ENV                                 # Perl module that imports environment variables as scalars or arrays
   23. Memoize                         # Make functions faster by trading space for time
   24. Net::SSH::Perl                # Is used to connect to different machine

4. Creating a Module.
ANSWER:


Creating a Module
-------------------------

package NewModule;

use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);

require Exporter;

@ISA = qw(Exporter AutoLoader);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
@EXPORT = qw( );
$VERSION = '0.01';

# Preloaded methods go here.
# Autoload methods go after =cut, and are processed by the autosplit program.

1;
__END__





use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
The vars pragma is a way of declaring your global variables. Any variable listed here is available throughout the entire package scope.

require Exporter;
This loads the Exporter module, which allows you to export variables and subroutines into the calling packages namespace when the module is used with the use statement.

@ISA = qw(Exporter AutoLoader);
By placing a module name in the @ISA array, we are saying that the current package is a subclass (in the object-oriented sense) of that package. In practical terms, this means that if we try to use a method NewModule->foo and the &foo subroutine is not found in the NewModule package, then Perl will also check for &Exporter::foo and &AutoLoader::foo as well. If those aren't found, Perl will check Exporter's parents and AutoLoader's parents, and so on up the tree.

@EXPORT = qw( );
Any variables or subroutines listed here will automatically be placed into the calling package's namespace. It is important to document these in order to prevent namespace conflicts.

$VERSION = '0.01';
All modules should have a version number. This helps with version control. In addition, it allows you to do:

The references to preloaded and autoloaded methods are only relevant if you are using the AutoLoader module. Don't use the AutoLoader module unless you know what you're doing, it's generally not worth the trouble.

1;
When a module is loaded (via use) the compiler will complain unless the last statement executed when it is loaded is true. This line ensures that this is the case (as long as you don't place any code after this line). It's Perl's way of making sure that it successfully parsed all the way to the end of the file.

__END__
Anything after this token is ignored by the compiler. This is generally where you will place your documentation.



h2Xs command is used to create module:

Command: h2xs -AXc -n NewModule
[~/modules],2:05pm% h2xs -AXc -n NewModule
Writing NewModule/NewModule.pm
Writing NewModule/Makefile.PL
Writing NewModule/test.pl
Writing NewModule/Changes
Writing NewModule/MANIFEST
[~/modules],2:05pm% cd NewModule/
[~/modules/NewModule],2:05pm% ls
Changes MANIFEST Makefile.PL NewModule.pm test.pl



Install the module
Now we've got everything written, we can try installing the module. The general procedure for installing any Perl module is:

perl Makefile.PL
make
make test
make install




.

Copyright 2009 Kunal Saxena Inc. All rights reserved