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;
Sepearte First name and last name by using PERL regular expressions
Validate Info-Perl Script
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; }
Print Message--Perl Script
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>")); } }
Password encryption-Perl Script
sub encrypt_pass { my( $passwd) = @_; $passwd = lc($passwd); my $salt = substr $passwd, 0, 2; my $encryptedpass = crypt($passwd, $salt); return 1; }
Convert to Seconds--Perl script
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; }
File size and 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 }
Convert to minute-Perl script
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; }
Login screen using Perl
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; }
Huge text file comparator
#!/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;
Parse Input - Perl Script
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; }
Get colored difference - Perl Script
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 ); }
Perl function to compare two dates
#! /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 }
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 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"; # }
Cross Referencing script
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";
Random Bunch Creation in Perl
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; }
NASDAQ Status checker using Perl
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__
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 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;
Perl script to find files older than x minutes
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
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 => 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
Date Arimatic
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
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 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
Perl function to check whether the passed path 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
Perl function to check whether file or dir name passed to it 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
Perl function to check whether the passed path is runnable or not
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