skip to main | skip to sidebar

Perl Programming Language Tutorial

Pages

  • Home
 
  • RSS
  • Twitter
Thursday, October 25, 2012

Sepearte First name and last name by using PERL regular expressions

Posted by Raju Gupta at 12:18 PM – 1 comments
 

We are using PERL regular expression.
We are using 3 functions prxparse,prxmatch and prxposn.

Prxparse takes regularexpression and retutns a pattern identification number for the compiled regular expression.

Prxmatch takes a pattern identification numbar and character value and return the position where the egularexpression finds a match

prxposn returns a value for captured buffer.   

 
data Names;
   input name  $32.;
   datalines;
Raj Gupta
Sam Mark
Jenny Derak
John Michel
;
run;

data FirstLastNames;
   length first last $ 16;
   keep first last;
   retain re;
   if _N_ = 1 then
      re = prxparse('/(\w+)\s(\w+)/');
   set Names;
   if prxmatch(re, name) then 
      do;
         last = prxposn(re, 1, name);
         first = prxposn(re, 2, name);
      end;
run;


[ Read More ]
Read more...
Wednesday, October 24, 2012

Validate Info-Perl Script

Posted by Raju Gupta at 9:00 PM – 0 comments
 

It checks whether the length of HTML field values are greater than or equal to some specified minimum length, if not it will report an error. Field name, minimum length are the parameters to this subroutine.   

sub validate_info {
    my ($name,$field, $minlen, $allow_blank) = @_;
    my $count = 0;
    my $errcnt;
    if (length($field) >= $minlen) {
        $errcnt = 0;   ## ok
    } else {
        if ((length($field) == 0) && ($allow_blank eq 'Y')) {
            $errcnt = 0;
        } else {
            &print_message("Minimum length for $name is $minlen","W");
            $errcnt = 1;  ## Counts as an error
        }
    }
    return $errcnt;
}
 

[ Read More ]
Read more...

Print Message--Perl Script

Posted by Raju Gupta at 12:11 PM – 0 comments
 

This is a Subroutine which is called by the scripts where some message is to be printed on the browser. $message and $type are the parameters passed by the scripts. This subroutine formats the $message accordingly to $type. $type indicates the severity of the message by giving some colour value.   

 
sub print_message {

 my ($message, $type) = @_;

 if ($type =~ /E/i) {
  print center(h3("<font color=red size=+2>$message</font>"));
 }
 elsif ($type =~ /W/i) {
  print center(h3("<font color=purple>$message</font>"));
 }
 else {
  print center(h4("<font color=darkblue>$message</font>"));
 }

}


[ Read More ]
Read more...
Tuesday, October 23, 2012

Password encryption-Perl Script

Posted by Raju Gupta at 6:00 PM – 0 comments
 
It is used to encrypt the password. Password to be encrypted is passed as agrument to this subroutine when called.

 
sub encrypt_pass {
 my( $passwd) = @_;
 $passwd = lc($passwd);
 my $salt = substr $passwd, 0, 2;
 my $encryptedpass = crypt($passwd, $salt);
   
    return 1;
}

[ Read More ]
Read more...

Convert to Seconds--Perl script

Posted by Raju Gupta at 12:01 PM – 0 comments
 
It takes time in minutes as parameter and converts it into time in seconds.

 
sub convert_to_seconds {
    my $time_in_seconds = 0;
    my $time_in_minutes = $_[0];

    if ((int($time_in_minutes) <= 0) || (length($time_in_minutes) == 0)) {
         $time_in_minutes = 120;
    }

    $time_in_seconds = int($time_in_minutes) * 60; 
    return $time_in_seconds; 
}

[ Read More ]
Read more...
Monday, October 22, 2012

File size and modified time

Posted by Raju Gupta at 11:56 AM – 0 comments
 
When we pass the file name (include full path) as parameter,It will give us the size of the file and last modified time.

 
sub getFileStats {
 my $filename = $_[0];       ## includes full path
 my $not_applicable = 'N/A';

 # get the stats.  This returns nulls if no file exists
 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($filename);
 
 if($mtime != undef) {
  # format datetime
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime($mtime);  
  $year += 1900;
  if ($min < 10) {
   $min = "0$min";
  }

  $mon = $mon + 1; ## zero based
  
  my $str_time = "$mon/$mday/$year $hour:$min";
  return ($size, $str_time);
 } else {
  return ($not_applicable, $not_applicable);
 }

 #------------------------------------------------------------------- 
 # For reference here are the stats we get for this filename
 #
 # 0 dev      device number of filesystem
 # 1 ino      inode number
 # 2 mode     file mode  (type and permissions)
 # 3 nlink    number of (hard) links to the file
 # 4 uid      numeric user ID of file's owner
 # 5 gid      numeric group ID of file's owner
 # 6 rdev     the device identifier (special files only)
 # 7 size     total size of file, in bytes
 # 8 atime    last access time in seconds since the epoch
 # 9 mtime    last modify time in seconds since the epoch
 # 10 ctime    inode change time (NOT creation time!) in seconds since the epoch
 # 11 blksize  preferred block size for file system I/O
 # 12 blocks   actual number of blocks allocated  
}


[ Read More ]
Read more...

Convert to minute-Perl script

Posted by Raju Gupta at 9:30 AM – 0 comments
 
It takes time in seconds as parameter and converts it into time in minutes.

 
sub convert_to_minutes {
    my $time_in_seconds = $_[0];
    my $time_in_minutes = 0;

    if ((int($time_in_seconds) <= 0) || (length($time_in_seconds) == 0)) {
         $time_in_seconds = 36000;      ## 36000 = 600 minutes  * 60 seconds/minute
    }

    $time_in_minutes = int($time_in_seconds) / 60; 
    return $time_in_minutes; 
}


[ Read More ]
Read more...
Sunday, October 21, 2012

Login screen using Perl

Posted by Raju Gupta at 8:00 PM – 0 comments
 

This code snippet takes one parameter for default user and displays a login screen asking for user name and password . It aslo provides an option to navigate to two different pages depending on the option selected.   

 
sub print_login_form {

 my($defaultuser ) = @_;
 my $return_script_flag="0";
 my $user_pass_check="0";
 my($userbox) = textfield(-name=>'userid',-size=>9,-default=>$defaultuser,-maxlength=>8);

 my($passwordbox) = password_field(-name=>'passwd', -size=>9, -maxlength=>8);
 my ($tech_type) = "<input type='hidden' name='tech_type' />";  
 my ($user_pass_check) = "<input type='hidden' name='user_pass_check' />";  
 my %techlabels = ('TDMA' => 'TDMA', 
   'GSM' => 'GSM');
 my @techvalues = reverse(sort keys %techlabels);
 my(@radiobuttons) = radio_group( -name=>'technology',
      -values=>@techvalues,
      -labels=>%techlabels); 

 my ($loginbutton) = "<input name='Login' type='submit' value='Login'  />"  ;
 
 print <<TABLE;
 <center>
 <table border=0 cellspacing=10 cellpadding=5>
 <tr>
  <td>
   <font color=darkblue size=+1><b>User ID:</b></font>
  </td>
  <td>
   $userbox
  </td>
 </tr>
 <tr>
  <td>
   <font color=darkblue size=+1><b>Password:</b></font>
  </td>
  <td>
   $passwordbox
  </td>
 </tr>
 <tr>
  <td>
   <font color=darkblue size=+1>$radiobuttons[0]</font>
  </td>
  <td>
   <font color=darkblue size=+1>$radiobuttons[1]</font>
  </td>
 </tr>
 <tr>
  <td> $tech_type </td>
 </tr> 
  <tr>
   <td>
    $user_pass_check
   </td>
  </tr>
 <tr>
  <td colspan=2>
   <center>$loginbutton</center>
  </td>
 </tr>
 </table>
 </center>
TABLE

 print endform;
 return 1;
}

[ Read More ]
Read more...

Huge text file comparator

Posted by Raju Gupta at 11:49 AM – 0 comments
 

You may want to compare two very large text files containing delimited data, for millions of rows, unsorted and in a random order. The ideal solution Excel would fail because of it's incapability to support rows > 1048596. For even thousands of rows, Excel would put the system to an irresponsive state, as the data we are going to compare are not in proper order in both the files.

This piece of code, enables the user to compare File1 against File2 and list the differences. One of the file will be compared agaisnt the other and the selection of what to compare against what, will be chosen based upon the file size, (larger file is compared against), in order to increase the efficiency. The output is displayed on the screen, which is the entire row that mismatched (or not found). Output can of course be redirected to a file using the UNIX redirection operator. > filename.txt


 #!/usr/bin/perl

print "File 1 : ";
chomp($file1=); #get the name of File 1
print "File 2 : "; 
chomp($file2=); #get the name of File 2

open TESTFILE, "<", $file1 or die "Cannot open File : $file1\nError : $!\n"; # Abort if unable to read file 1
open TESTFILE2, "<", $file2 or die "Cannot open File : $file2\nError : $!\n"; # Abort if unable to read file 1

@file_1_data= (-s $file1 < -s $file2) ?  : ; #choose what to compare against what depending 
    #upon the file size so as to reduce the number of 
           #comparison operations.
@file_2_data= (-s $file1 < -s $file2) ?  : ;

$file_1_current_line;   #contains data being read from file 1
$line_counter;    #to keep track of the current line
$matched_flag=0;   #flag to indicate if match found

foreach (@file_1_data) {
 s/\s+//g;    #replace unnecessary white space to nothing
 $file_1_current_line=$_; #start from line no. 1
 $line_counter ++;  #Increment the line counter as it traverses.
  foreach ( @file_2_data ) { #do it for each row in file 2
  s/\s+//g;  #replace unnecessary white space to nothing
   if(/($file_1_current_line)/) {  #if different from the data just read from file 1, 
    # print "matched\n"; #a debugging message to display the user as soon as a match is found
   $matched_flag=1;        #set to indicate match found and the comparison can continue with next row of file 1
   last;   #similiar to saying break;
    }
   }
 print "\nNot matched\nLine no: $line_counter\n$file_1_current_line\n" 
      if $matched_flag==0; #display the row not matched
   $matched_flag=0;      #reset the match flag to continue with next row.
}

close TESTFILE;    #close both the files
close TESTFILE2;


[ Read More ]
Read more...
Saturday, October 20, 2012

Parse Input - Perl Script

Posted by Raju Gupta at 12:09 PM – 0 comments
 

It reads data from $source that is delimited by the $delimiter characters, and returns a hash reference. The hash keys are the period-limited keywords. The input, $source, may be either a filename (in which case the file is opened, read, and closed), a FILEHANDLE, or a text string.

 
sub parse_input {
  my ($delimiter,$source) = @_;
  my %A = ();
  my $input;

  if (ref($source) eq "GLOB") { # read the entire file handle contents
                                # if a GLOB was passed in
    $input = join("",<$source>);
  } elsif ( -s $source ) { # input is coming from a filename
    open(F,"< $source");
    $input = join("",);
    close(F);
  } else { # a simple text string was passed in
    $input = $source;
  }

  my @words = split($delimiter,$input);
  for my $word (@words) {
    next if ($word =~ /^\#/);
    $word =~ s/^(\s+)?(.+)(\s+)?$/$2/;
    my ($k,@v) = split('=',$word);
    my ($t,$attr) = split('\.',$k);
    my $value = join('=',@v);
    if (defined($attr)) {
      if ($attr =~ /e(ncrypted_)?passw(or)?d/i) {
 $value = _decrypt($value);
 $attr = "password";
      }
      $A{uc($t)}->{uc($attr)} = $value;
    } else {
      $A{uc($k)} = $value;
    }
  }
  return \%A;
}


[ Read More ]
Read more...

Get colored difference - Perl Script

Posted by Raju Gupta at 12:07 PM – 0 comments
 
It is used to set the font color of the row values of a table having two columns. None of the rows should be null to set the font color. Left hand side column is set with dark blue color and right hand side column with dark red color.

 
sub get_colored_differences {
 my ( $left_side, $right_side) = @_;
 my @left_side_array = split ( /\^/, $left_side );
 my @right_side_array = split ( /\^/, $right_side );
 my $left_side_size = scalar ( @left_side_array );
 my $right_side_size = scalar ( @right_side_array );
 
 #if ( $left_side_size == $right_side_size ) {
  if ($left_side_size,$right_side_size>0) {
  
  my $idx = 0;
  for ($idx = 0; $idx < $left_side_size; $idx++) {
   if ( "$left_side_array[0]" eq "$right_side_array[0]" ) {
    $left_side_array[$idx] = "" . $left_side_array[$idx] . "";
    $right_side_array[$idx] = "" . $right_side_array[$idx] . "";
   }
  }

  $left_side = join ( '^', @left_side_array );
  $right_side = join ( '^', @right_side_array );
 }
   
 return ( $left_side, $right_side );
}


[ Read More ]
Read more...

Perl function to compare two dates

Posted by Raju Gupta at 11:38 AM – 3 comments
 

This function can be used to compare two dates using PERL. The function accepts two string(date) arguments, let's say date1 and date2 and returns
0 - If the two dates are equal.
1 - If the date1 passed is greater than date2.
-1 - If the date1 passed is less than date2

Note: The Dates to be passed should be in the following format
YYYY-MM-DD HH:MI:SS

Please find here below Sample script in which this function is called:  

#! /usr/bin/env perl 

my $mstr_cdate1 = "2008-04-29 12:00:09"; 
my $mstr_cdate2 = "2008-04-28 22:00:09"; 

my $mint_retval = fstr_compareDateAndTime($mstr_cdate1, $mstr_cdate2); 

print $mint_retval; 

********************************** 

Output in this case is 1 as date1 is greater than date2. 
 
 ########################################################################   
# Name                  : fstr_compareDateAndTime
#   
# Description           : compare two dates using Perl
#   
# Parameters            : 1. Date1  (string)   
#                         2. Date2  (string)   
#   
# Return                : Integer. This function can be used to compare two dates using PERL. The function accepts two string(date) #arguments, let's say date1 and date2 and returns
#    0    -  If the two dates are equal.
#    1    -  If the date1 passed is greater than date2.
#          -1    -  If the date1 passed is less than date2
#   
# Calls functions       : fstr_compareDateAndTime   
#   
# Executables Called    : None   
#   
# Perl Modules Used     : None   
######################################################################## 
sub fstr_compareDateAndTime($$)
{
 # answers how does date1 compare to date2
 # (greater than "1", less than "-1", or equal to "0")
 my ($mstr_date1, $mstr_date2) = @_;
 
 my @marr_date1;
 my @marr_date2;
 my $mint_limit =0;
 
 
 my ($mstr_onlydate1, $mstr_onlytime1) = split(/ /, $mstr_date1);
 push(@marr_date1,split(/-/, $mstr_onlydate1));
 push(@marr_date1,split(/-/, $mstr_onlytime1));
 
 my ($mstr_onlydate2, $mstr_onlytime2) = split(/ /, $mstr_date2);
 push(@marr_date2,split(/-/, $mstr_onlydate2));
 push(@marr_date2,split(/-/, $mstr_onlytime2));
 
 # compare up to the lesser number of elements
 # (like if one datetime only has a date and no time, don't try to compare time)
 if(@marr_date1 == @marr_date2) { $mint_limit = @marr_date1 }
 elsif (@marr_date1 > @marr_date2) { $mint_limit = @marr_date2 }
 elsif (@marr_date1 < @marr_date2) { $mint_limit = @marr_date1 }
 
 
 for (my $mint_count = 0; $mint_count < $mint_limit; $mint_count++)
 {
  if ($marr_date1[$mint_count] > $marr_date2[$mint_count]) { return 1; last; }# date1 greater than date2
  if ($marr_date1[$mint_count] < $marr_date2[$mint_count]) { return -1; last; }# date1 less than date2
 }
 return 0;# dates are equal
}
 

[ Read More ]
Read more...
Wednesday, October 17, 2012

Script to rotate any log file

Posted by Raju Gupta at 9:59 AM – 0 comments
 

This script creates a copy of standard out log files of Weblogic Server after it has reached a predefined size limit,renames it with current date & generates a fresh log file of zero byte size.


 #!/usr/bin/perl
# Name:       rotateLog.pl
# Script to rotate any log file.
# Usage: rotateLog.pl my.log
#
use strict;

my ( $LOGFILE, $MAXLOGS, $DELNUM );

$LOGFILE = $ARGV[0];
$MAXLOGS = 30;
print $LOGFILE;
# if ( -e $LOGFILE ) {

   my ( @LOGS, $LOG, $LASTNUM );
   @LOGS = `ls -1 $LOGFILE?*`;

   $DELNUM = ( scalar(@LOGS) - $MAXLOGS );
   if ( $DELNUM gt 0 ) { print "Need to delete $DELNUM files.\n"; }

   foreach $LOG( @LOGS ) {
      chomp($LOG);
      # Delete logs until less than MAXLOGS
      if ($DELNUM gt 0) {
         print "Deleting log $LOG.\n";
         unlink $LOG;
         $DELNUM = $DELNUM -1;
      }

      # Strip log number from log
      $LASTNUM = $LOG;
      $LASTNUM =~ s/$LOGFILE//g;
   }

   # Increment log number for new file
   $LASTNUM ++;
   $LASTNUM = sprintf("%03d", $LASTNUM);

   # Copy current log to backup
   print "Rotating $LOGFILE to $LOGFILE$LASTNUM.\n";
   system("/usr/bin/cp $LOGFILE $LOGFILE$LASTNUM");

   # Create replacement current log
   system("/usr/bin/cat /dev/null > $LOGFILE");

# }
# else {

  #  print "Error: Log file $LOGFILE not found.\n";

# }

[ Read More ]
Read more...

Cross Referencing script

Posted by Raju Gupta at 3:30 AM – 0 comments
 

Script to cross reference sybase tables and stored procedures of a given database with perl scripts (.cgi, .pl, .pm extensions)


  #!/ms/dist/perl5/bin/perl5.6

use strict;
use Sybase::DBlib;
use Benchmark;

my $t1 = new Benchmark;

if( scalar (@ARGV) < 2 ) {
 die "Need the directory of perl scripts and/or DB name!\n";
}

my $dir = $ARGV[ 0 ];
my $dbname = $ARGV[ 1 ];
my $user = $ARGV[ 2 ];
my $pass = $ARGV[ 3 ];
my $server = $ARGV[ 4 ];

my $dbh = new Sybase::DBlib( $user, $pass, $server ) or die "\nCannot login to $server\n";
my $db = $dbh->dbuse( $dbname );

opendir DIR, $dir or die "Cannot open directory $dir for read\n";

my @files = readdir( DIR );

closedir DIR;

my $sql = "select tab.name  from sysobjects tab where tab.type='U'";

my @tab;
my @col;

#Replace the nsql function to call using HASH

my $rc = $dbh->nsql( $sql, "ARRAY", sub{
          push @tab, $_[ 0 ];
          push @col, $_[ 1 ];
         });

if( $DB_ERROR ) {
 die "Error encountered during select of table names- $DB_ERROR\n";
}

my %TblHash;
my $temp;

foreach my $tab1 ( @tab ) {
 my $sql;

 $sql = "sp_depends $tab1";

 my @depends;

 $dbh->nsql( $sql, "ARRAY", sub{
         if(( defined($_[ 1 ] )) and ($_[ 1 ] eq "stored procedure" )){
          my $proc1 = substr($_[ 0 ],4);
          $proc1 =~ s/\s+//g;
          push @depends, $proc1;
         }
         });

 print "Searching for table - $tab1\n";

 foreach my $fl1 ( @files ) {
  if( $fl1 =~ 'cgi$|perl$|pm$|perl$' ) {

   open (FIL, "$dir/$fl1") or warn "cannot open - $fl1\n";
    
   my $line;

   while( $line =  ) {

    if( $line =~ $tab1 and $line !~ '^#') {
     if( $TblHash{$tab1} !~ $fl1 ) {
       $TblHash{$tab1} = $TblHash{$tab1}."$fl1,";
     }
    }
    else {
     foreach (@depends) {
      if( $line =~ $_ ) {
       if( $TblHash{$tab1} !~ $fl1 ) {
         $TblHash{$tab1} = $TblHash{$tab1}."$fl1,";
       }
      }
     }
    }
   }
   close FIL;
  }
 }
}     

open OUT,">report.txt" or die "cannot open report for write!\n";

foreach (keys (%TblHash)) {
 my @scriptfiles = split /,/,substr($TblHash{$_},0,-1);

 print OUT "\n--------------------------\n";
 print OUT $_,"\n--------------------------\n";

 foreach (@scriptfiles){
  print OUT $_,"\n";
 }

 print OUT "\n++++++++++++++++++++++++++\n\n";
}

close OUT;


$dbh->dbclose();

my $t2 = new Benchmark;

my $timediff = timediff( $t2, $t1 );

print "Total time for exec - ",timestr($timediff),"\n";

[ Read More ]
Read more...
Tuesday, October 16, 2012

Random Bunch Creation in Perl

Posted by Raju Gupta at 9:50 AM – 0 comments
 

It creates bunches of n size randomly from a list of values supplied.
Example:-----------
List: 1,2,3,4,5,6,7,8,9,10,11
Bunch Size: 2
Result:
Bunch# 1: 7 2
Bunch# 2: 3 9
Bunch# 3: 4 11
Bunch# 4: 6 5
Bunch# 5: 8 1
Bunch# 6: 10


 
use strict;

my @main_arr = (1,2,3,4,5,6,7,8,9,10,11);
my $bunch_size = 2;
my @bunch_arr = &randomBunch(@main_arr,$bunch_size);
my $bunch_cnt = 0;

foreach ( @bunch_arr) {
    $bunch_cnt++;
    print "Bunch# $bunch_cnt:          ";
    foreach  (@{$_}) {
        print "$_  ";
    }
    print "
";
}
sub randomBunch {
    my ($arr_ref,$bunch_size) = @_;
    my @arr = @$arr_ref;
    my ($index,$element);
    my @ret_arr;
    my $num_bunch = int( ($#arr+1) / $bunch_size ) + 1;
    for (1 .. ($#arr+1) ) {
        my @bunch_arr = ();
        for (1 .. $bunch_size) {
            if ($#arr + 1 > 0) {
                $index = int(rand @arr);
                push @bunch_arr,"${arr[$index]}";
                splice(@arr, $index, 1); ##delete it from main arr
            }
        }
        push @ret_arr,@bunch_arr;
        if ( $#arr < 0 ) {
            last;
        }
    }
    return @ret_arr;
}


[ Read More ]
Read more...

NASDAQ Status checker using Perl

Posted by Raju Gupta at 9:48 AM – 0 comments
 

Perl script to check the nasdaq trader website to check for system/ipo updates and send email


 $| = 1;
use strict;
use Date::Calc qw( Today_and_Now );

use CGI qw( :all );

use HTML::Tree;
use HTML::TableExtract;
use LWP::UserAgent;


my $app = $ARGV[0];
my %alertStatus = ('url' => 0);
my $severity = 0;
my $desc = '';
my $from = 'NASDAQ';
my $alertCounter = 1;

my ($year,$month,$day,$hour,$min,$sec) = Today_and_Now();
my $today = sprintf ("%4s-%02s-%02s-%02s:%02s:%02s",$year,$month,$day,$hour,$min,$sec);

my $proxy = $ENV{$app."_proxy"};

my $url = $ENV{$app."_url"};
$url = 'http://www.nasdaqtrader.com/Trader.aspx?id=MarketSystemStatus' if(!$url);

my $sleep = $ENV{$app."_sleep"};
$sleep = 50;

my %alertHash = (
     'sr' => 'ExchangeAlert',
     'id' => 'NASDAQ',
     'monType' => 'Alert',
     'e' => $region."iedmon",
     'URL:NASDAQ_URL' => $url
    );

print STDERR "
checkNASDQAStatus: $today: Starting checkNASDQAStatus
";
print STDERR "checkNASDQAStatus: proxy - $proxy, URL - $url, check interval - $sleep
";
print STDERR "checkNASDQAStatus: -------------------------------------------------------
";

my $ua = LWP::UserAgent->new;
$ua->proxy(['http'], $proxy );

my $te = new HTML::TableExtract( headers => [qw( Date Time Status )] );

while( 1 ){
 checkNASDAQStatus();

 print STDERR "sleeping...
";
 sleep 55;
}

sub checkNASDAQStatus{
 my $request = new HTTP::Request(GET=>$url);
 my $response = $ua->request( $request );

 if( $response->{_rc} !~ /^2dd/ ){
  if( $alertStatus{'url'} == 0 ){
   $severity = 5;
   $desc = "Request to NASDAQ URL - $url failed.  Return code - $response->{_rc}
";

   $desc =~ s/ /_/g;

   publishError( $severity, $desc );
  }

  print STDERR "Request to $url failed.  Return code - $response->{_rc}
";

  sleep( 55 );
  next;
 }
 else{
  clearAlert() if( $alertStatus{'url'} == 1 );
 }

 eval{
  $te->parse( $response->{_content} );
 } or die( "Unable to parse NASDAQ website
");

 foreach my $ts( $te->table_states() ){
  foreach my $row ($ts->rows) {
   next if( ( $$row[2] =~ /All Systems are Operating Normally|There are no messages available/ ) || ( $$row[2] eq '' && $$row[0] =~ /No Status Messages/ ) );
   $$row[1] =~ s/s+$//g;
   $$row[2] =~ s/s+$//g;

   $$row[1] =~ s/(;|,|
)/-/g;
   $$row[2] =~ s/(;|,|
)/-/g;

   if( not exists $alertStatus{$$row[2]} ){
    $severity = 9;
    $desc = $$row[2];

    $alertStatus{$$row[2]} = 1;
    $alertHash{AlertTime} = $$row[1];
    $desc =~ s/ /_/g;
    publishError( $severity, $desc );

#    print STDERR "NASDAQ Alert - $$row[2]";
   }
  }
 }
}

sub publishError{
 my $severity = shift;
 my $desc = shift;

 $alertHash{pub} = 'checkNASDAQStatus';
 $alertHash{severity} = $severity;

 $alertHash{ty} = 'Alert~Message'.$alertCounter;
 $alertHash{monDesc} = $desc;

 if( !$alertStatus{'url'} ){
      
            ##Dont send Mail for WebSite Non-Availability..alert is send to Mon and IChat 
     if ($desc !~ /Request to NASDAQ URL/){
  my %mailDetails = ();
  my $mailBody = '';
      
  $mailBody = table( {-border=>1},
      Tr(
       th( 'Alert time' ),
       th( 'Alert Description' )
      ),
      Tr(
       td( $alertHash{AlertTime} ),
       td( $mailDesc )
      )
     );

  $mailBody .= br();
  $mailBody .= br();
  $mailBody .= 'click '.a( {-href=>$url}, 'HERE' ).' to open NASDAQ Market System Status web page';

         $mailDetails{'to'} = "rajugupta15@gmail.com";
         $mailDetails{'from'} = 'rajugupta15@gmail.com';
         $mailDetails{'type'} = 'text/html';
         $mailDetails{'body'} = $mailBody;
         $mailDetails{'subject'} = "NASDAQ ALERT";
 
         send_mail( %mailDetails );
    }

 }

 $alertCounter++;
}

sub clearAlert{
 $alertStatus{'url'} = 0;
}

__END__

[ Read More ]
Read more...
Monday, October 15, 2012

Fix Message Reader from Log

Posted by Raju Gupta at 9:31 AM – 0 comments
 

Various subroutines of the package FixUtil can be used to read fix message (tag, value pair). Fix message can be extracted. Tag and Value can be identified. Numeric Tag can be converted in to English readable format. It also provide functionality to selectively print only few tags of interest.


 #!/usr/local/bin/perl 

package FixUtil;

# GetTagValue is to convert fix message in to tag value pair. The parameter passed is single fix message or portion of a fix message.

sub GetTagValue
{
  my ($record)=@_;
  my @tagValuePair=split(/;/,$record);
  my $count=0;
  while ($count < @tagValuePair)
  {
    if ( $tagValuePair[$count] =~ /=/)
    {
      ($tag,$value)=split(/=/,$tagValuePair[$count]);
      $tagValue{$tag}=$value;
    }
    $count++;

  }
  return %tagValue;
}

# CleanUp is to convert a log statement to a clean fix message starting with 8=FIX and ending with 10=000 

sub CleanUp {
  my ($record)=@_;
  $record=~s/^.*8=FIX/8=FIX/g;
  $record=~s/10=000.*$/10=000/g;
  return $record;
}

# GetHeader is to get log part before the fix message 

sub GetHeader {
  my ($record)=@_;
  $record=~s/8=FIX.*$//g;
  return $record;
}

# PrintTagValues is to print selected tags from TagValue hash created by GetTagValue. 
# $indent = (integer) number of spaces. This is useful if you would like to indent New, Cancel and Replace messages with different indentation.
# $info = reference to an array which contains list of tags to be printed. e.g. the list should contain 38, 31, 32 if we are interested only in quantities. Following function will only print those three tags.
# $records = reference to hash of tag value created by GetTagValue function 

sub PrintTagValues {
  my ($indent,$info,$records)=@_;
  my $indentation=" ";
  while($indent > 0)
  {
    $indentation=$indentation." ";
    $indent--;
  }
  my $count=0;
  if( $$info[0] =~ "All")
  {
    foreach $tag (keys(%{$records}))
    {
      print "$indentation $tag ($TagValuePair{$tag}) = $records->{$tag} \n";
    }
  }
  else
  {
    while ($count < @{$info})
    {
      print "$indentation $$info[$count] ($TagValuePair{$$info[$count]}) = $records->{$$info[$count]} \n";
      $count++;
    }
  }
  print "\n";
}

%TagValuePair = ( "1","Account",
  "2","AdvId",
  "3","AdvRefID",
  "4","AdvSide",
  "5","AdvTransType",
  "6","AvgPrice",
  "7","BeginSeqNo",
  "8","BeginString",
  "9","BodyLength",
  "10","CheckSum",
  "11","ClOrdID",
  "12","Commission",
  "13","CommType",
  "14","CumQty",
  "15","Currency",
  "16","EndSeqNo",
  "17","ExecID",
  "18","ExecInst",
  "19","ExecRefID",
  "20","ExecTransType",
  "21","HandlInst",
  "22","IDSource",
  "23","IOIid",
  "24","IOIOthSvc",
  "25","IOIQltyInd",
  "26","IOIRefID",
  "27","IOIShares",
  "28","IOITransType",
  "29","LastCapacity",
  "30","LastMkt",
  "31","LastPrice",
  "32","LastShares",
  "33","LinesOfText",
  "34","MsgSeqNum",
  "35","MsgType",
  "36","NewSeqNo",
  "37","OrderID",
  "38","OrderQty",
  "39","OrdStatus",
  "40","OrdType",
  "41","OrigClOrdID",
  "42","OrigTime",
  "43","PossDupFlag",
  "44","Price",
  "45","RefSeqNum",
  "46","RelatdSym",
  "47","Rule80A",
  "48","SecurityID",
  "49","SenderCompID",
  "50","SenderSubID" );
1;

[ Read More ]
Read more...

Perl script to find files older than x minutes

Posted by Raju Gupta at 5:30 AM – 0 comments
 

This script can be used to find files in a windows directory older than 40 min. List can be emailed to a user also.
Script can be modified to find files older than whatever timeframe is needed.

 
use File::Find;
$receiver = "team@gmail.com";
$message = "Files waiting for more than 40 minutes in E:/cd/sci/Prod/outbound directory

";
$sendmail = "no";

use NTsendmail;
opendir(MYDIR, "E:/cd/sci/Prod/outbound") or die ("Cannot open dir to read");
chdir("E:/cd/sci/Prod/outbound");
@name = readdir(MYDIR);

foreach $x (@name) {

  
 if ( -s $x and -M $x > 0.028 )   { 
 $write_secs = (stat($x))[9];
 $sendmail = "yes";
 $message .= sprintf " %s  updated on %s

", $x,scalar localtime($write_secs);
 
 
 }
}
 closedir DIR;
 #print $message;

if ( $sendmail eq "yes" ) {

 $ENV{"NTsendmail"} = "smtp.language-tutorial.com";
 $mail = new NTsendmail;
 $sender = "admin@language-tutorial.com";
 $subject = "File Alert";
 $mail->send($sender, $receiver, $subject, $message);

}


# end of script


[ Read More ]
Read more...
Sunday, October 14, 2012

Perl function to check whether the passed path is empty or not

Posted by Raju Gupta at 9:19 AM – 0 comments
 

The function makes sure that the path (directory and/or file) passed to it as an Input parameter is empty or not.


 use constant SUCCESS => 1; 
use constant FAILURE => 0; 

sub fint_isnot_empty ($)
{

        #Arguments: The path to be checked.
        my($mstr_path) = @_;

        my $mint_retval = SUCCESS; #This holds the return value

        #if the path is a file then the size should be checked else if
        # its a directory,
        #the number of elements within should be checked.
        $mint_retval = FAILURE if (-f $mstr_path and -z $mstr_path);

        if (-d $mstr_path)
        {
                opendir(HNDLDIR,$mstr_path);
                my @marr_path_files = readdir(HNDLDIR);
                close(HNDLDIR);

                #even if the dir is empty, because of . and .. the
                #count will be atleast 1.
                $mint_retval = FAILURE if ($#marr_path_files lt 2);
        }

        #If there is no path existing as specified, setup to return
        #failure.
        $mint_retval = FAILURE if (! -e $mstr_path);

        return $mint_retval;
} # end of fint_isnot_empty

[ Read More ]
Read more...

Date Arimatic

Posted by Raju Gupta at 8:00 AM – 0 comments
 

The shell script uses perl to find the date 'n' days back


 #!/bin/ksh

# this script is used in date subtraction.
# the script uses perl command
# Similarly, the date before â??nâ?? days can be
# obtained by multiplying 86400 * n in the 
# place of 86400

Days=1

echo "
Yesterday's date...
"
a=`perl -e '$d = time();
   @f = localtime($d - 86400);
         printf "%04d %02d %02d
",$f[5]+1900, $f[4]+1, $f[3];
                                                   ' $Days`
echo $a

echo "
Two days back date...
"
b=`perl -e '$d = time();
   @f = localtime($d - 172800);
      printf "%04d %02d %02d
",$f[5]+1900, $f[4]+1, $f[3];
                                          ' $Days`
echo $b

[ Read More ]
Read more...

Perl function to trim leading and trailing spaces from a string

Posted by Raju Gupta at 2:00 AM – 1 comments
 

Leading and trailing spaces, if any present, are trimmed and the string is returned back to the caller. If a NULL string is passed, the function does nothing.


 sub fstr_trim ($)
{
        # Arguments: The string to be trimmed.
        my ($mstr_original) = @_;
        #if a null/empty string is passed, just quit
        return unless(defined $mstr_original);

        $mstr_original =~ s/[s]+$//g;
        $mstr_original =~ s/^[s]+//g;
        $mstr_original =~ s/^ +//g;
        $mstr_original =~ s/ +$//g;
        return($mstr_original);
} # end of fstr_trim

[ Read More ]
Read more...
Saturday, October 13, 2012

Perl function to check whether the passed path is write able or not

Posted by Raju Gupta at 9:13 AM – 1 comments
 

The function makes sure that the path (directory and/or file) passed to it as an Input parameter is write able or not.

 
use constant SUCCESS => 1; 
use constant FAILURE => 0; 

sub fint_is_write ($)
{
        #Arguments: The path to be checked.
        my($mstr_path) = @_;
        my $mint_retval = SUCCESS; #This holds the return value
        $mint_retval = FAILURE if (!-w $mstr_path);
        return $mint_retval;
} # end of fint_is_write



[ Read More ]
Read more...

Perl function to check whether file or dir name passed to it readable or not

Posted by Raju Gupta at 9:12 AM – 1 comments
 

The function makes sure that the path (directory and/or file) passed to it as an Input parameter is readable or not  

 
use constant SUCCESS => 1; 
use constant FAILURE => 0; 

sub fint_is_read ($)
{
        #Arguments: The path to be checked.
        my($mstr_path) = @_;
        my $mint_retval = SUCCESS; #This holds the return value
        $mint_retval = FAILURE if (!-r $mstr_path);
        return $mint_retval;
} # end of fint_is_read


[ Read More ]
Read more...

Perl function to check whether the passed path is runnable or not

Posted by Raju Gupta at 7:48 AM – 1 comments
 

The function makes sure that the path (directory and/or file) passed to it as an Input parameter is run able or not.


use constant SUCCESS => 1; 
use constant FAILURE => 0; 

sub fint_is_run ($)
{
        #Arguments: The path to be checked.
        my($mstr_path) = @_;
        my $mint_retval = SUCCESS; #This holds the return value
        $mint_retval = FAILURE if (!-x $mstr_path);
        return $mint_retval;
} # end of fint_is_run

[ Read More ]
Read more...
Newer Posts
Subscribe to: Posts (Atom)
  • Popular
  • Recent
  • Archives

Popular Posts

  • Perl function to compare two dates
    This function can be used to compare two dates using PERL. The function accepts two string(date) arguments, let's say date1 and date2...
  • File size and modified time
    When we pass the file name (include full path) as parameter,It will give us the size of the file and last modified time. sub getFileSt...
  • Perl function to check whether file or dir name passed to it readable or not
    The function makes sure that the path (directory and/or file) passed to it as an Input parameter is readable or not   use constant SU...
  • Perl script to find files older than x minutes
    This script can be used to find files in a windows directory older than 40 min. List can be emailed to a user also. Script can be modi...
  • Sepearte First name and last name by using PERL regular expressions
    We are using PERL regular expression. We are using 3 functions prxparse,prxmatch and prxposn. Prxparse takes regularexpression an...
  • Perl function to check whether the passed path is empty or not
    The function makes sure that the path (directory and/or file) passed to it as an Input parameter is empty or not. use constant SUCCESS ...
  • Perl function to trim leading and trailing spaces from a string
    Leading and trailing spaces, if any present, are trimmed and the string is returned back to the caller. If a NULL string is passed, the func...
  • Fix Message Reader from Log
    Various subroutines of the package FixUtil can be used to read fix message (tag, value pair). Fix message can be extracted. Tag and Value ca...
  • Login screen using Perl
    This code snippet takes one parameter for default user and displays a login screen asking for user name and password . It aslo provides a...
  • Script to rotate any log file
    This script creates a copy of standard out log files of Weblogic Server after it has reached a predefined size limit,renames it with current...
Powered by Blogger.

Archives

  • ▼  2012 (24)
    • ▼  October (24)
      • Sepearte First name and last name by using PERL re...
      • Validate Info-Perl Script
      • Print Message--Perl Script
      • Password encryption-Perl Script
      • Convert to Seconds--Perl script
      • File size and modified time
      • Convert to minute-Perl script
      • Login screen using Perl
      • Huge text file comparator
      • Parse Input - Perl Script
      • Get colored difference - Perl Script
      • Perl function to compare two dates
      • Script to rotate any log file
      • Cross Referencing script
      • Random Bunch Creation in Perl
      • NASDAQ Status checker using Perl
      • Fix Message Reader from Log
      • Perl script to find files older than x minutes
      • Perl function to check whether the passed path is ...
      • Date Arimatic
      • Perl function to trim leading and trailing spaces ...
      • Perl function to check whether the passed path is ...
      • Perl function to check whether file or dir name pa...
      • Perl function to check whether the passed path is ...
 

Followers

Labels

  • File Searching Example (1)
  • Perl Date Example (2)
  • Perl Encryption Example (1)
  • Perl File Example (2)
  • Validation Example (1)
 
 
© 2011 Perl Programming Language Tutorial | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger