perl date time quandry - perl

I am trying to use perl date/time and also get file date info.
I started with this routine:
sub getTime {
#arrayDate = localtime(time);
($strSec,$strMin,$strHr,$strDate,$strMo,$strYr,$strDOW,$strDOY,$strDST) = localtime(time);
$strYr += 1900;
$strMo += 1;
if (length($strMo) < 2) { $strMo = "0" . $strMo }
if (length($strDate) < 2) { $strDate = "0" . $strDate }
if (length($strHr) < 2) { $strHr = "0" . $strHr }
if (length($strMin) < 2) { $strMin = "0" . $strMin }
if (length($strSec) < 2) { $strSec = "0" . $strSec }
$strDateTime = "$strYr$strMo$strDate $strHr:$strMin:$strSec";
}
Which worked fine.
Then I needed to get file date info using $file1date = ctime(stat($flatFile1)->mtime);.
Here is where the confusion begins. If I add use File::stat and use Time::localtime to get the file date to work, the first routine stops working and gives me this as output: 1900010 0:0:Time::tm=ARRAY(0x9a7b98)
So in order to get both to work I had to change the date routine to this:
sub getTime {
$strMon = localtime->mon();
$strMday = localtime->mday();
$strYear = localtime->year();
$strHour = localtime->hour();
$strMin = localtime->min();
$strSec = localtime->sec();
$strYear += 1900;
$strMon += 1;
if (length($strMon) < 2) { $strMon = "0" . $strMon }
if (length($strMday) < 2) { $strMday = "0" . $strMday }
if (length($strHour) < 2) { $strHour = "0" . $strHour }
if (length($strMin) < 2) { $strMin = "0" . $strMin }
if (length($strSec) < 2) { $strSec = "0" . $strSec }
$strDateTime = "$strYear$strMon$strMday $strHour:$strMin:$strSec";
}
... which I'm sure is not efficient. What's the right way to do this?

I'd like to advise you to use Time::Piece.
The above core module alters the behavior of localtime to return an object of type Time::Piece that has a strftime function. The following are your two goals performed with this module:
use strict;
use warnings;
use Time::Piece;
use File::stat;
print "Current time: " . localtime->strftime("%Y%m%d %H:%M:%S") . "\n";
print "Script created: " . localtime(stat($0)->ctime)->strftime("%Y%m%d %H:%M:%S") . "\n";
Outputs:
Current time: 20140624 19:18:17
Script created: 20140624 15:54:36

I wouldn't say that there's anything wrong with the second method. My only suggestion would be to use sprintf to format $strDateTime instead of a block of if statements:
sub getTime {
$strDateTime = sprintf("%04d%02d%02d %02d:%02d:%02d",
localtime->year() + 1900,
localtime->mon() + 1,
localtime->mday(),
localtime->hour(),
localtime->min(),
localtime->sec());
}
For reference: the field %04d means a decimal (d) field of length 4, padded with 0. Using fixed-length, padded decimal fields is a quick and easy way to format numbers.
You can see the whole guide on sprintf in the documentation.

Related

How to use a string as an operator?

It is possible to use a string as an operator?
my $ip = "10 > 0.2 && 5 < 1";
if($ip)
{
print "Hello\n\n";
}
else
{
print "wrong\n";
}
How to consider the string > && < as an operator?
A non-empty string will always evaluate to true if you use it like this. What you want to do is to evaluate the content of the string as code, and perl provides the eval-statement for exactly this purpose:
my $ip = "10 > 0.2 && 5 < 1";
if( eval($ip) )
{
print "Hello \n\n";
}
else
{
print "wrong\n";
}
This will give the expected output "wrong".

Perl script appending date

Am running this perl script ever day on my server and am getting the below output for the script. I am trying to modify the script to also include the current hour as part of the output. How can I go about doing this?
This is my current script:
#!/usr/bin/perl
#Prism Performance log Parser
use strict;
my $cbal_total;
my $cbal_count =0;
my $stck_total = 0;
my $stck_count =0;
my $chg_total = 0;
my $chg_count =0;
my $rmac_total = 0;
my $rmac_count =0;
my $rmd_total = 0;
my $rmd_count =0;
my $cbalT;
my $stckT;
my $rmacT;
my $rmdT;
my $chgT;
my $total;
my $count;
my $cbal;
my $stck;
my $hour;
my $chg;
my $rmac;
my $rmd;
my $lesThresh=0;
my $gtThresh=0;
my $stck_lesThresh=0;
my $stck_gtThresh=0;
my $rmd_lesThresh=0;
my $rmd_gtThresh=0;
my $chg_lesThresh=0;
my $chg_gtThresh=0;
my $rmac_lesThresh=0;
my $rmac_gtThresh=0;
my %CheckBal;
my %SubTypeCheck;
my %charging;
my %remoteAct;
my %remoteDct;
my $chgkey;
my $cbalkey;
my $stckkey;
my $rmackey;
my $rmdkey;
my #value;
my $ct;
my $component;
my $component2;
while (my $line =<>) {
chomp;
s/\r//g;
my #f = split(/\|/, $line);
my $i;
$hour = substr($f[0],11,2);
for ($i==0;$i<=100; $i++) {
if (($f[$i]=~m/CBAL/) && ($f[$i]!~m/CBAL,100/)) {
$component="CBAL";
$cbal=$f[$i];
$cbalkey="$hour,$component";
if (!exists($CheckBal{$cbalkey})) {
$cbal_count=0;
$cbal_total=0;
$lesThresh=0;
$gtThresh=0;
}
$cbalT = substr($cbal,index($cbal,",T=")+3,index($cbal,"\n"));
if ($cbalT <= 300) {
$lesThresh++;
}else{
$gtThresh++
}
$cbal_total +=$cbalT;
$cbal_count ++;
#$CheckBal{$cbalkey} =($cbal_total).",".($cbal_count).",".($lesThresh).",".$gtThresh.",".($cbal_total/$cbal_count);
$CheckBal{$cbalkey} =($cbal_count).",".($cbal_total).",".($cbal_total/$cbal_count).",".($lesThresh).",".$gtThresh;
}elsif($f[$i]=~m/STCK/){
$component="STCK";
$stck=$f[$i];
$stckkey="$hour,$component";
if (!exists($SubTypeCheck{$stckkey})) {
$stck_count=0;
$stck_total=0;
$stck_lesThresh=0;
$stck_gtThresh=0
}
$stckT = substr($stck,index($stck,",T=")+3,index($stck,"\n"));
if ($stckT <= 300) {
$stck_lesThresh++;
}else{
$stck_gtThresh++
}
$stck_total +=$stckT;
$stck_count ++;
# $SubTypeCheck{$stckkey} =($stck_total).",".($stck_count).",".($stck_lesThresh).",".$stck_gtThresh.",".($stck_total/$stck_count);
$SubTypeCheck{$stckkey} =($stck_count).",".($stck_total).",".($stck_total/$stck_count).",".($stck_lesThresh).",".$stck_gtThresh;
}elsif($f[$i]=~m/CHG/){
$component="CHG";
$chg=$f[$i];
$chgkey="$hour,$component";
if (!exists($charging{$chgkey})) {
$chg_count=0;
$chg_total=0;
$chg_lesThresh=0;
$chg_gtThresh=0
}
$chgT = substr($chg,index($chg,",T=")+3,index($chg,"\n"));
if ($chgT <= 300) {
$chg_lesThresh++;
}else{
$chg_gtThresh++
}
$chg_total +=$chgT;
$chg_count ++;
# $charging{$chgkey} =($chg_total).",".($chg_count).",".($chg_lesThresh).",".$chg_gtThresh.",".($chg_total/$chg_count);
$charging{$chgkey} =($chg_count).",".($chg_total).",".($chg_total/$chg_count).",".($chg_lesThresh).",".$chg_gtThresh;
}elsif(($f[$i]=~m/RMAC/) && ($f[$i]!~m/RMAC,96/)){
$component="RMAC";
$rmac=$f[$i];
$rmackey="$hour,$component";
if (!exists($remoteAct{$rmackey})) {
$rmac_count=0;
$rmac_total=0;
$rmac_lesThresh=0;
$rmac_gtThresh=0
}
$rmacT = substr($rmac,index($rmac,",T=")+3,index($rmac,"\n"));
if ($rmacT <= 300) {
$rmac_lesThresh++;
}else{
$rmac_gtThresh++
}
$rmac_total +=$rmacT;
$rmac_count ++;
# $remoteAct{$rmackey} =($rmac_total).",".($rmac_count).",".($rmac_lesThresh).",".$rmac_gtThresh.",".($rmac_total/$rmac_count);
$remoteAct{$rmackey} =($rmac_count).",".($rmac_total).",".($rmac_total/$rmac_count).",".($rmac_lesThresh).",".$rmac_gtThresh;
}elsif(($f[$i]=~m/RMD/) && ($f[$i]!~m/RMD,96/)){
$component="RMD";
$rmd=$f[$i];
$rmdkey="$hour,$component";
if (!exists($remoteDct{$rmdkey})) {
$rmd_count=0;
$rmd_total=0;
$rmd_lesThresh=0;
$rmd_gtThresh=0
}
$rmdT = substr($rmd,index($rmd,",T=")+3,index($rmd,"\n"));
if ($rmdT <= 300) {
$rmd_lesThresh++;
}else{
$rmd_gtThresh++
}
$rmd_total +=$rmdT;
$rmd_count ++;
# $remoteDct{$rmdkey} =($rmd_total).",".($rmd_count).",".($rmd_lesThresh).",".$rmd_gtThresh.",".($rmd_total/$rmd_count);
$remoteDct{$rmdkey} =($rmd_count).",".($rmd_total).",".($rmd_total/$rmd_count).",".($rmd_lesThresh).",".$rmd_gtThresh;
}
}
}
print "Balance Check\n";
print "Hour,Task,Total Transactions,Total Processing Time/ms,Average TPS/ms,<300 ms,>300 ms\n";
unless(%CheckBal){
print "No record found for STCK\n";
}
foreach (sort keys %CheckBal){
print $_.",".$CheckBal{$_}."\n";
}
Current Output:
Balance Check
Hour,Task,Total Transactions,Total Processing Time/ms,Average TPS/ms,<300 ms,>300 ms
06,CBAL,17987,13131831,730.073441930283,4295,13692
07,CBAL,17911,13579801,758.182178549495,3970,13941
08,CBAL,228,98643,432.644736842105,100,128
Desired Output:
Balance Check
date,Hour,Task,Total Transactions,Total Processing Time/ms,Average TPS/ms,<300 ms,>300 ms
20140528,06,CBAL,17987,13131831,730.073441930283,4295,13692
20140528,07,CBAL,17911,13579801,758.182178549495,3970,13941
20140528,08,CBAL,228,98643,432.644736842105,100,128
To get the current hour, use Time::Piece
use strict;
use warnings;
use Time::Piece;
print localtime->strftime("%H"), "\n";
How to insert that functionality into your script is an exercise for you.

COnverting atime from LDAP to Perl

I have created a script in Perl to connect to LDAP, retrieve values and post them to a CSV file. The values I am retrieving via a query are d"distinguished name, userAccountControl & pwdLastSet. I can pull and parse the first two results correctly and post them to the CSV file, but the pwdLastSet is returning WIN32::OLE=HASH(0x.......). I have tired sprintf, hex(), and the results are either the WIN32 value or 0. I am expecting something 18 digits in length. Thanks for the help.
#!/usr/bin/perl
use xSV;
use Win32;
use Win32::OLE;
# use strict;
.
.
.
.
while ($line = <GROUPS>) {
chomp($line);
if ($line =~ m/^ user .*/) {
$line =~ s/^ user.\s//;
my ($objRootDSE, $strDomain, $strUsername, $objConnection, $objCommand, $objRecordSet, $strDN, $arrSplitResponse, $strLName, $strFName, $strUserType);
use constant ADS_SCOPE_SUBTREE => 2;
# Get domain components
$objRootDSE = Win32::OLE->GetObject('LDAP://RootDSE');
$strDomain = $objRootDSE->Get('DefaultNamingContext');
# Get username to search for
$strUsername = $line;
# Set ADO connection
$objConnection = Win32::OLE->new('ADODB.Connection');
$objConnection->{Provider} = 'ADsDSOObject';
$objConnection->Open('Active Directory Provider');
# Set ADO command
$objCommand = Win32::OLE->new('ADODB.Command');
$objCommand->{ActiveConnection} = $objConnection;
$objCommand->SetProperty("Properties", 'Searchscope', ADS_SCOPE_SUBTREE);
$objCommand->{CommandText} = 'SELECT distinguishedName, userAccountControl, pwdLastSet FROM \'LDAP://' . $strDomain . '\' WHERE objectCategory=\'user\' AND samAccountName = \'' . $strUsername . '\'';
# Set recordset to hold the query result
$objRecordSet = $objCommand->Execute;
# If a user was found - Retrieve the distinguishedName
if (!$objRecordSet->EOF) {
$strDN = $objRecordSet->Fields('distinguishedName')->Value;
$strAcctControl = $objRecordSet->Fields('userAccountControl')->Value;
$strpwdLS = sprintf($objRecordSet->Fields('pwdLastSet')->Value);
#arrSplitResponse = split(/,/, $strDN);
$strLName = substr($arrSplitResponse[0],3);
if ($strLName =~ m/\\$/) {
$strLName = substr($strLName,0,-1);
}
$strFName = $arrSplitResponse[1];
if ($strFName =~ m/OU=/) {
$strUserType = $strFName;
$strFName = "";
$strUserType = substr($strUserType,3);
} else {
$strUserType = substr($arrSplitResponse[2],3);
}
if ($strAcctControl == 512) {
$strAcctControl = "Active";
} else {
$strAcctControl = "Disabled";
}
} else {
print "No user found";
}
&debug("Match!: $line in $group\n");
$csv->print_data(
AccountName => $line,
LastName => $strLName,
FirstName => $strFName,
SYSGenericAcct => $strUserType,
AccessLevel => $group,
AccessCapability => "User",
Description => $desc,
Status => $strAcctControl,
LastPwdChange => $strpwdLS
);
} else {
$group = $line;
chomp($desc = <GROUPS>);
chomp($group2 = <GROUPS>);
&debug("$group\n$desc\n$group\n");
}
}
Use Net::Ldap to search AD server. It is fast and it is portable. It is possible to search AD server from other hosts, even from linux. It is a fast and mature module.
You could also do some debug, using Data::Dumper.
use Data::Dumper;
...
print Dumper($strpwdLS);
I found this thread: http://code.activestate.com/lists/pdk/3876/
# Calculate password age in days
my $PWage;
my $LastPW = $item->{pwdLastSet};
my $fRef = ref ($LastPW);
my ($Hval, $Lval);
if ($fRef eq 'Win32::OLE' )
{
$Hval = $LastPW->HighPart;
$Lval = $LastPW->LowPart;
my $Factor = 10000000; # convert to seconds
my $uPval = pack("II",$Lval,$Hval);
my ($bVp, $aVp) = unpack("LL", $uPval);
$uPval = ($aVp*2**32+$bVp)/$Factor;
if ($uPval != 0)
{
$uPval -= 134774*86400; #Adjust for perl time!
my $EpochSeconds = time;
$PWage = ($EpochSeconds - int($uPval))/(60*60*24) ;
$PWage =~ s/\..*$//;
}
}

Perl sub doesn't want to work with passed objects as parameters

I pass two Date::Manip::Date objects, perfectly valid dates to my sub:
sub get_duration {
my $duration;
my #val;
my $from = $_[0]->new_date();
my $to = $_[1]->new_date();
# $from->parse("2012-03-06");
# $to->parse("2012-03-07");
print $from . " ".$to. "<-- <br />";
my #f = $from->value();
if ($f[0] == 2012) {
$from->config("ConfigFile",$HOLIDAYS_2012);
} elsif ($f[0] == 2013) {
$from->config("ConfigFile",$HOLIDAYS_2013);
} elsif ($f[0] == 2014) {
$from->config("ConfigFile",$HOLIDAYS_2014);
} elsif ($f[0] == 2015) {
$from->config("ConfigFile",$HOLIDAYS_2015);
}
my #t = $to->value();
if ($t[0] == 2012) {
$to->config("ConfigFile",$HOLIDAYS_2012);
} elsif ($t[0] == 2013) {
$to->config("ConfigFile",$HOLIDAYS_2013);
} elsif ($t[0] == 2014) {
$to->config("ConfigFile",$HOLIDAYS_2014);
} elsif ($t[0] == 2015) {
$to->config("ConfigFile",$HOLIDAYS_2015);
}
print "from " . #f ." to ". #t."<br>";
my $delta = $from->calc($to, "business");
print $from->calc($to, "business") . " <-";
#val = $delta->value();
if ($to->is_business_day()) {
$duration = $val[3]+1;
} else {
$duration = $val[3];
}
return $duration;
}
I get the output
Date::Manip::Date=HASH(0xacdf7a0) Date::Manip::Date=HASH(0xacdfb50)<--
from 0 to 0
<-
Software error:
Can't call method "value" on an undefined value at '#val = $delta->value();'
That is the two dates are passed all right, I got NO errors when it tries to set their config files, Regardless, the value arrays #t and #f are empty and it breaks down as soon as I try to get the delta.
However if I uncomment the two lines
$from->parse("2012-03-06");
$to->parse("2012-03-07");
(hence ignoring the parameters)
It works just fine as intended.
There's something I'm missing about passing objects in Perl I suspect?
Firstly
&get_overlap_duration($saved[$i][5], $saved[$i][6], $saved[$i][7], $saved[$i][8])
Is called
I've printed the #saved values and they're correct, they're strings:
2012-03-06, 2012-03-08, 2012-03-05, 2012-03-07
Then inside get_overlap_duration those strings are
my $from1 = new Date::Manip::Date;
my $to1 = new Date::Manip::Date;
my $from2 = new Date::Manip::Date;
my $to2 = new Date::Manip::Date;
$from1->parse($_[0]);
$to1->parse($_[1]);
$from2->parse($_[2]);
$to2->parse($_[3]);
Then there's there is a call for get_duration for instance $duration = get_duration($from2, $to1);
I've checked the server error log there were no complaints apart from the software error displayed in the browser.
The problem is that on the following line:
my $delta = $from->calc($to, "business");
It's not returning a valid object. Which likely means that something in the calc() function is failing. Since "business" is not a valid date. And if you read the Date::Manip::Calc man page, the mode parameter is only legal when you pass in two date objects before that and you've only passed one.

Does any one have a working script of LoadRunner Automation API?

Currently I am writing Perl script that creates LoadRunner scenario, execute the test, collect the result, recover the environment and repeat the cycle again with different scenario variables.
I don't have a problem creating new scenario, adding generator, adding 2 groups + script + the run-time settings. But I am having a problem with:
Setting scenario schedule from "Scenario" to "Group".
Setting schedule per group
This the snippet of the code:
use strict;
use v5.10;
use Win32::OLE;
use Win32::OLE::Enum;
use Win32::OLE::Variant;
use Data::Dumper;
use Win32::OLE::Const 'LoadRunner Automation Library';
use constant False => Variant(VT_BOOL,'');
use constant True => Variant(VT_BOOL,1);
my $lrEngine = Win32::OLE->new('wlrun.LrEngine') or die "oops\n";
my $lrScenario = $lrEngine->Scenario();
my $rc = $lrScenario->new(0, 1); # do not save previous, Regular vusers based scenario
if ($rc != 0) {
print "Win32::OLE::LastError: ".Win32::OLE::LastError()."\n";
print "lrScenario->new(0, 1):rc: $rc\n";
}
# snip-snipped - add generator
# snip-snipped - add #groups definition
foreach my $group (#groups) {
print "scriptName: $group->{scriptName}\n";
my $scriptLocation = $group->{scriptLocation};
my $scriptName = Variant(VT_BSTR|VT_BYREF, $group->{scriptName});
{ # add $group->{scriptName} script
$rc = $lrScenario->Scripts->Add($scriptLocation, $scriptName);
if ($rc != 0) {
print "Win32::OLE::LastError: ".Win32::OLE::LastError()."\n";
print "lrScenario->Scripts->Add($scriptLocation, $scriptName):rc: $rc\n";
}
}
#############################################################################
my $groupName = Variant(VT_BSTR|VT_BYREF, $group->{groupName});
{ # add $group->{groupName} group
$rc = $lrScenario->Groups->Add($groupName);
if ($rc != 0) {
print "Win32::OLE::LastError: ".Win32::OLE::LastError()."\n";
print "lrScenario->Groups->Add:rc: $rc\n";
}
$rc = $lrScenario->Groups->Item($groupName)->AddVusers($scriptName, $hostname, 3);
if ($rc != 0) {
print "Win32::OLE::LastError: ".Win32::OLE::LastError()."\n";
print "lrScenario->Groups->Item($groupName)->AddVusers:rc: $rc\n";
}
}
#############################################################################
# snip-snipped - change group script run time setting
}
my $scheduleName = Variant(VT_BSTR|VT_BYREF, 'Schedule123');
my $lrManualScheduleData = $lrScenario->ManualScheduler->AddSchedule($scheduleName, lrGroupSchedule); # Scenario schedule mode
if (!$lrManualScheduleData) {
say "Win32::OLE::LastError: ".Win32::OLE::LastError();
say "lrScenario->ManualScheduler->AddSchedule:rc: $rc";
}
$rc = $lrScenario->ManualScheduler->SetCurrentSchedule($scheduleName);
if ($rc != 0) {
say "Win32::OLE::LastError: ".Win32::OLE::LastError();
say "lrScenario->ManualScheduler->SetCurrentSchedule:rc: $rc";
}
print "\$lrScenario->ManualScheduler->SetScheduleMode($scheduleName, lrGroupSchedule):";
$lrScenario->ManualScheduler->SetScheduleMode($scheduleName, lrGroupSchedule);
#LrManualScheduleMode -> lrGroupSchedule = 1, lrScenarioSchedule = 0
say "Win32::OLE::LastError: ".Win32::OLE::LastError();
$lrManualScheduleData->{'InitAllBeforeRun'} = 'True';
$lrManualScheduleData->{'DurationMode'} = 1;
$lrManualScheduleData->{'Duration'} = 60 * 60;
$lrManualScheduleData->{'RampupBatchSize'} = 1;
$lrManualScheduleData->{'RampupMode'} = lrRampupByGroupBatches;
$lrManualScheduleData->{'RampupTimeInterval'} = 5;
$lrManualScheduleData->{'RampdownBatchSize'} = 1;
$lrManualScheduleData->{'RampdownMode'} = lrRampupByGroupBatches;
$lrManualScheduleData->{'RampdownTimeInterval'} = 5;
$rc = $lrScenario->ManualScheduler->{'ScenarioStartTimeMode'} = 0; # Start scenario without delay
#test
say "$scheduleName: ".$lrScenario->ManualScheduler->Schedule($scheduleName)->{'Duration'}; # returns 300
I have the same problem. Setting those properties and then calling either setschedulemode or setcurrentschedule doesn't seem to work. The only workaround I have found is to use the setscheduledata method passing in xml. You will need to get the current xml for the scheduledata and then change the xml, passing in the modified xml to the setscheduledata method. Hopefully this helps
lrManualScheduleData data = engine.Scenario.ManualScheduler.get_Schedule("Schedule 1");
String scheduleXML,errStr;
int returncode = data.getScheduleData(out scheduleXML, out errStr);
// Manipulate the XML to set whatever schedule you want
data.SetScheduleData(scheduleXML, out errStr);