Showing posts with label Perl Modules. Show all posts
Showing posts with label Perl Modules. Show all posts

Tuesday, September 14, 2010

chdir in perl for changing working directory

usage:
chdir EXPR
chdir(EXPR)

Changes the working directory to EXPR, if possible. If EXPR is omitted, changes to directory specified by $ENV{HOME}, if not set, changes to $ENV{LOGDIR} directory . if none of these is set then does nothing.

Returns 1 upon success, 0 otherwise.
Example:
chdir("C:\temp\working_dir\");

Using file copy and move in perl

copy function is used for copying a file from one location to another. Its present in File::copy module.
 
use File::Copy; 
copy("C:\temp\file1", "C:\tmp\file1.orig") or die "copy failed: $!";  # will make a copy of file1
copy("C:\temp\Fileout.txt", *STDOUT) or die "copy failed: $!";  # will print Fileout.txt into STDOUT
move("C:\temp\Fileout.txt", "C:\temp2\Fileout.txt") or die "move failed: $!";    # will move first argument to 2nd argument

This doesnt support features like creating backups of file, recursive copying etc. these functions also support file handles as argument.

Thursday, April 22, 2010

BEGIN, INIT, CHECK, UNITCHECK, END : Five different code blocks

These are different types of code blocks available in Perl, which get executed during start and end of any Perl program. One can have more than one of these blocks in any Perl program, and will get executed in appropriate moment.

BEGIN: It gets executed in Compile time, as soon as possible, even before the rest of the file is parsed. There may be multiple BEGIN{} blocks and they will be executed in FIFO.

END : It is executed as late as possible, that is, after Perl has finished running the program and just before the interpreter is being exited, even if it is exiting as a result of a die() function. There may be multiple END{} Blocks, within a file. They will be executed in LIFO(reverse) order. END blocks are not executed when you run Perl with -c switch i.e. It's not called in compile time.

UNITCHECK: It's called after the unit which defined them has been compiled. The main program file and module it loads are compilation units.

CHECK: These are run just after initial compile phase ends and before the run time begins in LIFO order. These are used by Perl compile suite to save the compiled state of the program.

INIT : These are run just before Perl run time begins execution in FIFO Order.

INIT, CHECK, UNITCHECK, blocks are used to catch the transition between compilation phase and execution phase of main program.
##########################################################
# One example program for Perl mod
print "8. Ordinary code runs at runtime.\n";

 END { print "12. Read perlmod for the rest of the story.\n" }
 INIT { print " 6. INIT blocks run FIFO just before runtime.\n" }
 UNITCHECK { print " 4. And therefore before any CHECK blocks.\n" }

 print "9. It runs in order, of course.\n";

 BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" }
 CHECK { print " 5. CHECK blocks run LIFO after all compilation.\n" }
 BEGIN { print " 2. So this line comes out second.\n" }
 INIT { print " 7. Run this again, using Perl's -c switch.\n" }
 END { print "11. END blocks run LIFO at quitting time.\n" }
 UNITCHECK { print " 3. UNITCHECK blocks run LIFO after each file is compiled.\n" }

 print "10. It merely _looks_ like it should be confusing.\n";

Wednesday, April 7, 2010

including/Using/Require Perl Modules in Program

There are many ways to include modules/packages in your program.

Use Module;

Or
Use Module List;

Which is exactly equivalent to

    BEGIN { require Module; import module; }
                   or
    BEGIN { require Module; import Module List; }
                   or
    require "Module.pm";
    import Module;

All perl modules have extensions.pm, use assumes this so you don't have to spell it out explicitly as "Modules.pm" instead you can say use Module;

Following two statements:

require Module;
require "Module.pm";

differ from each other. In first case, any double colon ( my::module) will be translated to  system's directory separator e.g."/", while in second case you will have to give module name with path literally.


With "require" one can get into following problem:
require myModule;
$some = myModule::somefunc();  # Need to make myModule:: accessible

use myModule;               # Import Names from myModule
$some = somefunc();

require myModule;
$some=somefunc();  # Error: No main::somefunc(),    so be careful in this case. solution is as follow

Above problem can be solved as following:
require "myModule.pm";
import myModule;
$some=somefunc();

Command Line inclusion
For including module from command line use following command:
C:\>perl -MmyModule myprogram.pl

For more information on -M switch check perlrun in perldoc
For more information on this refer to this link.
or check in chapter 11. modules in Perl Programming.

Monday, March 22, 2010

Setting environment variable using Perl Programs

Most of the time you may need to add the path of some directories where your code files are present or even your perl modules are there, and you want to use them.

Since %ENV is a special Hash in Perl, which contains values for all of your environment variables. So you can set any variables just like other hash variable in Perl.
So you can add following directories in your Path variable as:

$ENV{PATH} = 'C:\bin; C:\mymodule';

In this way it will replace your previous path to the one you are adding, but that will be till the program runs.

For Adding path in addition to existing path do it like following:

my $path = $ENV{PATH};
$path = $path . ';C:\bin; C:\mymodule';
$ENV{PATH} = $path;
print "\n\n $ENV{PATH}";


Similarly other variables can also be set.
You can check whether it's added or not by :

print $ENV{PATH};

Friday, March 19, 2010

Plain Old Documentation( POD) in perl

If you know how to write the perl codes then you should also know "How to document your script for better user interface". When you run script then if any of the wrong input should be told by script and user should be able to know how to use your script.

So the solution is use of POD::Usage module from perl. If you want to know more on basics of POD refer to this link. This link has good explanation on pod2usage.


pod2usage will print a usage message for the invoking script (using its embedded pod documentation) and then exit the script with the desired exit status. The usage message printed may have any one of three levels of "verboseness": 

Verbose = 0; Only SYNOPSIS
Verbose = 1; SYNOPSIS along with OPTIONS(command line arguments)
Verbose = 2; Full manual Page

Default Exit status: 2, verbose: 0
If exit status < 2, default Verbose = 1, else default verbose = 0
If verbose = 0, default exit status = 2, else default exit =1

If exit status < 2, output printed on STDOUT, otherwise on STDERR.

Usage:
use POD::Usage;

my $message_text = "This text precedes the usage message.";
my $exit_status = 2;
my $verbose_level = 0;
my $filehandle = \*STDERR;

pod2usage($message_text); # Will print a message immediately before printing usage message

pod2usage($exit_status); # Prints usage message depending upon exit status

pod2usage( { -message => $message_text ,
                    -exitval => $exit_status ,
                    -verbose => $verbose_level,
                    -output => $filehandle } );

Hash Keys for pod2usage(Arguments): Refer to this page for more help

-message : To print message before usage


-exitval : value to be passed to exit().


-verbose : Describes Level of usage message to be printed


-output : File handle where to print usage e.g. STDOUT, STDERR or any file


-input : A reference to a filehandle from which the invoking script's pod documentation should be read. Default is $0 i.e. current file.

-sections : Can print sections described in this section list as string e.g. "NAME|SYNOPSIS|OPTIONS", but only when verbose is 99.


-pathlist :A list of directory paths. If input file not in current directory then used.

-noperldoc : It will call perldoc if verbose >2.


A good example for using pod2usage(), for more refer to this link 

=================================================================

use Getopt::Long; 
use Pod::Usage;

my $args = @ARGV; # After GetOptions @ARGV will be undefined
GetOptions(
       'opt=s'    => \$option,
       'help'     => \$help,
       'man'      => \$man,
     ) or pod2usage( -message => "Try \"perl $0 -help\" for more information", exitval => 2);



pod2usage( -verbose => 1 ) if( $help || !$args);

pod2usage(-verbose => 2) if($man);
;1
__END__
 
=head1 NAME
 
   sample - Using GetOpt::Long and Pod::Usage
 
=head1 SYNOPSIS
 
   sample [options] [file ...]
 
   Options:
   -help brief help message
   -man  full documentation
   -opt  Option value
 
=head1 OPTIONS
 
=over 8
 
=item B<-help>
 
   Print a brief help message and exits.
 
=item B<-man>
 
   Prints the manual page and exits.

=item B<-opt>
 
   Takes some integer value
 
=back
 
=head1 DESCRIPTION
 
   B<This program> will read the given input in opt and do something
   useful with the contents thereof.
 
=cut

#=================================================================
Some important Links:
POD TUTORIAL
POD USAGE IN PERLDOC
PERLPOD IN PERLDOC




Friday, March 12, 2010

Use of caller in Perl

Caller or Caller Expr
Returns the context of the current subroutine call. In scalar context, returns the caller's package name if there is a caller, that is, if we're in a subroutine or eval or require, and the undefined value otherwise. In list context, returns
#      0            1            2
($package, $filename, $line ) = caller;


With EXPR, it returns some extra information that the debugger uses to print a stack trace. The value of EXPR indicates how many call frames to go back before the current one
# 0                       1       2           3             4
($package, $filename, $line, $subroutine, $hasargs,

 #    5                6              7             8           9           10
$wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
= caller($i);

(caller 1)[3] will give the name of the calling subroutine.
($package, $filename, $line ) = caller; or

($package, $filename, $line ) = caller 1; # Both of these are equivalent

@caller = caller 0; #will return whole information about the calling subroutine