Monday, March 29, 2010

Perl Functions & Keywords : a summary

Here are Perl's functions (including things that look like functions, like some keywords and named operators). Some functions may appear in more than one place just because they can be categorize in more than one place.

SCALARs or strings Functions:

chomp, chop, chr, crypt, hex, index, lc, lcfirst, length, oct, ord, pack, q//, qq//, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, y///

Regular expressions and pattern matching Functions

m//, pos, quotemeta, s///, split, study, qr//, tr///

Numeric functions

abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt, srand

Functions for real @ARRAYs

pop, push, shift, splice, unshift

Functions for list data

grep, join, map, qw//, reverse, sort, unpack

Functions for real %HASHes

delete, each, exists, keys, values

Input and output functions
binmode, close, closedir, dbmclose, dbmopen, die, eof, fileno, flock, format, getc, print, printf, read, readdir, rewinddir, say, seek, seekdir, select, syscall, sysread, sysseek, syswrite, tell, telldir, truncate, warn, write

Functions for fixed length data or records

pack, read, syscall, sysread, syswrite, unpack, vec

Functions for filehandles, files, or directories

-X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename, rmdir, stat, symlink, sysopen, umask, unlink, utime, mkpath


Miscellaneous functions

defined, dump, eval, formline, local, my, our, reset, scalar, state, undef, wantarray

Functions for processes and process groups
alarm, exec, fork, getpgrp, getppid, getpriority, kill, pipe, qx//, setpgrp, setpriority, sleep, system, times, wait, waitpid

Low-level socket functions

accept, bind, connect, getpeername, getsockname, getsockopt, listen, recv, send, setsockopt, shutdown, socket, socketpair

System V interprocess communication functions

msgctl, msgget, msgrcv, msgsnd, semctl, semget, semop, shmctl, shmget, shmread, shmwrite

Fetching user and group info

endgrent, endhostent, endnetent, endpwent, getgrent, getgrgid, getgrnam, getlogin, getpwent, getpwnam, getpwuid, setgrent, setpwent

Fetching network info

endprotoent, endservent, gethostbyaddr, gethostbyname, gethostent, getnetbyaddr, getnetbyname, getnetent, getprotobyname, getprotobynumber, getprotoent, getservbyname, getservbyport, getservent, sethostent, setnetent, setprotoent, setservent

Time-related functions

gmtime, localtime, time, times

Keywords related to the control flow of your Perl program
caller, continue, die, do, dump, eval, exit, goto, last, next, redo, return, sub, wantarray

Keywords related to switch
break, continue, given, when, default

(These are only available if you enable the "switch" feature. See feature and "Switch statements" in perlsyn.)

Keywords related to scoping
caller, import, local, my, our, state, package, use
(state is only available if the "state" feature is enabled. See feature.)
 
Keywords related to perl modules
do, import, no, package, require, use

Keywords related to classes and object-orientation
bless, dbmclose, dbmopen, package, ref, tie, tied, untie, use

Functions new in perl5

abs, bless, break, chomp, chr, continue, default, exists, formline, given, glob, import, lc, lcfirst, lock, map, my, no, our, prototype, qr//, qw//, qx//, readline, readpipe, ref, sub*, sysopen, tie, tied, uc, ucfirst, untie, use, when

* - sub was a keyword in perl4, but in perl5 it is an operator, which can be used in expressions.

Functions obsoleted in perl5

dbmclose, dbmopen

For more information on Perl Function Check this link

Wednesday, March 24, 2010

Executing and Capturing the output of a command on /bin/sh or cmd.exe using perl

qx/STRING/ or 'STRING' can be used for the purpose of capturing the output.
This interpolates the STRING and executes it as system command and returns the value as output of command execution. In scalar Context it returns the STDOUT value as a string( may be multi line).
STDOUT is referred as 1 while STDERR as 2.

Usage:
# To Captures both STDOUT and STDERR, Redirects STDERR(2) to STDOUT(1)
$output = `cmd 2>&1`;
 
# Captures Only STDOUT, STDERR is discarded ( STDERR is redirected to null) 
$output = `cmd 2>/dev/null`;  
 
# To capture only STDERR, and discard STDOUT, Order is Important
$output = `cmd 2>&1 1>/dev/null`;  
Using this following command you can redirect STDOUT and STDERR outputs to different files.
system("perl test.pl 1>test.stdout 2>test.stderr");

Check "`STRING`" in perlop (Part of perldoc) for more detail.

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};

Adding any directory path to environment variable "PATH" in windows

To add any path to your system's PATH environment variable to be used as search path please follow the steps below.

Right click on "My Computer" then select properties.


Now click on "Environment Variables" button. Now it will open up environment variables list.



Under "System Variables" select "Path" variable and "edit"


Go to last add ";" and add path of your directory path. Suppose you want to add "C:\Bin" in path variable. After adding it say "OK".

And It's done.









To check whether your path is added or not, open a new cmd.exe from run. and type "path". you will see you directory added there.

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




Monday, March 15, 2010

Tasklist and Taskkill in Windows to list the running process and kill required one

These are command line tools/Utility by windows for viewing all the running process from command prompt and then if any of the process is hanged or if you want to kill any one then that can also be done.

TaskList:

TASKLIST [/S system [/U username [/P [password]]]]
         [/M [module] | /SVC | /V] [/FI filter] [/FO format] [/NH]

Description:
    This command line tool displays a list of application(s) and associated task(s)/process(es) currently running on either a local or remote system.

Examples:
    TASKLIST
     TASKLIST /V
    TASKLIST /SVC : Displays services in each processes
    TASKLIST /S system12 /U domain\username /FO LIST : shows processes running in a remote system in list format
    TASKLIST /FI "IMAGENAME eq cmd.exe"


TsKill:
Ends a process.

TSKILL processid | processname [/SERVER:servername] [/ID:sessionid | /A] [/V]

Examples: TSKILL notepad.exe

TaskKill : This is a advanced form of TsKill utility.
 
TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]

Description:
    This command line tool can be used to end one or more processes.
    Processes can be killed by the process id or image name.

NOTE: Termination of remote processes will always be done forcefully
      irrespective of whether /F option is specified or not.

Examples:
    TASKKILL /F /IM notepad.exe /T
    TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
    TASKKILL /F /IM notepad.exe /IM mspaint.exe

Saturday, March 13, 2010

Some good example on usage of perl

Function: Split(/<reg exp>/, $scalar)
Use split function for splitting each character in a word or sentence, a example is given below. Return Value bu split is array of splitted  characters/word/symbols.
Code:
my $flist="my blog is http://batchandperl.blogspot.com";
my @klist = split(//, $flist);
print "@klist";



Output:
m y   b l o g   i s   h t t p : / / b a t c h a n d p e r l . b l o g s p o t . c o m






Split at ":" in any sentence
Code: @klist = split(/:/, $flist); # : will be removed and two array variables will get generated.
Output: my blog is http //batchandperl.blogspot.com

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

Creating Copy of File handles in Perl/Redirecting STDOUT to a file and screen

To Create an independent copy of file descriptor for the file handle: Use open with & mode
open(OLDOUT, ">&STDOUT" ) or die "Couldn't dup STDOUT: $!";
open(OLDIN, "<&STDIN" ) or die "Couldn't dup STDIN : $!";

Use open with the &= mode to create an alias for that filehandle's file descriptor:
open(OUTALIAS, ">&=STDOUT") or die "Couldn't alias STDOUT: $!";
open(INALIAS, "<&=STDIN") or die "Couldn't alias STDIN : $!";
open(BYNUMBER, ">&=5") or die "Couldn't alias file descriptor 5: $!";

If we try to create a copy of any file handle descriptor then actually we are calling dup (2) system call, by this we get two independent file descriptors whose file position, locks, and flags are shared, but which have independent stdio buffers. We can close any of file descriptor, which will not affect the other one.

But If we try to create a alias of any file handle then actually we are calling fdopen (3) stdio function. We get a single file descriptor with two stdio buffers accessed through two filehandles. Closing one filehandle closes the file descriptor of any aliases, but not their filehandles

# take copies of the file descriptors
open(OLDOUT, ">&STDOUT");
open(OLDERR, ">&STDERR");

# redirect stdout and stderr
open(STDOUT, "> /tmp/program.out")  or die "Can't redirect stdout: $!";
open(STDERR, ">&STDOUT")            or die "Can't dup stdout: $!";

# run the program
system($joe_random_program);

# close the redirected filehandles
close(STDOUT)                       or die "Can't close STDOUT: $!";
close(STDERR)                       or die "Can't close STDERR: $!";

# restore stdout and stderr
open(STDERR, ">&OLDERR")            or die "Can't restore stderr: $!";
open(STDOUT, ">&OLDOUT")            or die "Can't restore stdout: $!";

# avoid leaks by closing the independent copies
close(OLDOUT)                       or die "Can't close OLDOUT: $!";
close(OLDERR)                       or die "Can't close OLDERR: $!";

Tuesday, March 2, 2010

How to kill a process on Android device

To find the list of processes running on device just issue the command "adb shell ps", which will give list of all running processes and their PID's.

Issue "adb shell kill <PID>" where PID is the process ID to kill the process.

Running android application from command line using "am start ..." command

If you are a programmer you would like to run your application on android device form command line instead of clicking on the icon. So here is the solution for invoking your applications.

Use "am" command on command prompt. You can go to device's shell terminal by issuing "adb shell" command or you can club the am command with adb shell as "adb shell am start...". Following is the syntax for "am command".


> adb shell am
usage: am [start|instrument]
       am start [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
                [-c <CATEGORY> [-c <CATEGORY>] ...]
                [-e <EXTRA_KEY> <EXTRA_VALUE> [-e <EXTRA_KEY> <EXTRA_VALUE> ...]
                [-n <COMPONENT>] [-D] [<URI>]
       am instrument [-e <ARG_NAME> <ARG_VALUE>] [-p <PROF_FILE>]
                [-w] <COMPONENT>
For example, to start the Contacts application you can use
> adb shell am start -n com.google.android.contacts/.ContactsActivity

Refer to Instrumentation testing on android open source site