I have a list of extracted date timestamps. From this list I want to print timestamps between 8AM to 5PM foreach date/time. But my code below does not produce any output.
DATA:
2021-Sep-16 21:24:48
2021-Sep-17 03:31:05
2021-Sep-17 08:30:23
2021-Sep-17 09:42:43
2021-Sep-17 12:43:14
2021-Sep-17 14:43:23
2021-Sep-17 15:50:34
2021-Sep-17 16:50:35
2021-Sep-18 03:31:05
2021-Sep-18 08:30:23
2021-Sep-18 09:42:43
2021-Sep-18 12:43:14
2021-Sep-18 14:43:23
2021-Sep-18 15:50:34
2021-Sep-18 22:50:35
Expected output:
2021-Sep-17 08:30:23
2021-Sep-17 09:42:43
2021-Sep-17 12:43:14
2021-Sep-17 14:43:23
2021-Sep-18 08:30:23
2021-Sep-18 09:42:43
2021-Sep-18 12:43:14
2021-Sep-18 14:43:23
My code:
sub read_timestamps{
my $file = './logs/file.log';
open(IN, "<" ,"$file") or die "Couldn't open file $!";
open(OUT, ">" ,"_trash/tmp/raw/0-out.txt") or die "Couldn't open file $!";
my #content = <IN>;
my $start="08:00:00";
my $end = "17:00:00";
foreach $lines(#content){
if($lines = ~/$start/../$end/){
print OUT ("$1 \n") if($lines =~ /(\d{4}-\w+-\d{2} \d\d:\d\d:\d\d)/);
}
}
}
while (<>) {
my ( $h ) = / (\d+)/
or next;
print if $h >= 8 && $h < 17;
}
Related
sub logProcessing {
my $logpath = $File::Find::dir;
my $logfile = $_;
if ( $File::Find::name =~ m!$logDir/(.*?)/$pattern! and -d $File::Find::dir ) { $dirCount++ };
if ( $File::Find::name =~ m!$logDir/(.*?)/$pattern! and -f $File::Find::name ) { $fileCount++ };
if ( $File::Find::name =~ m!$logDir/(.*?)/$pattern! and -f $File::Find::name ) {
my $errorsSeen = `grep 'Errno 110' $File::Find::name|uniq`;
if ($errorsSeen ne "") {
$errorCount++;
my $hostname = $1;
my $lastModTime = localtime ( (stat $File::Find::name)[9] );
printf FILE "%3s %20s %50s %30s %50s\n", $hostname, 'Errno 110', $logpath, $logfile, $lastModTime;
}
else {
$nullCount++
}
}
}
The above is a code snippet from a Perl script which actually searches a bunch of log files and does a pattern search and prints a summary and sent it as a mail with attachment.
Wanted to refine the search for 3 patterns and don't want to increase the number of grep statement as the log files are 10k per day and that will increase the runtime of the script which now completes in approx 10 minutes.
As of now it searches 'Errno 110' but wants to add a combination of 'Errno 110', 'Errno 13' & 'Errno 43' and print the summary accordingly and as you see in the printf statement 'Errno 110' is hardcoded.
#!/usr/bin/perl
#
# program revision 1 - addded error filter
# and added error types
## Loading Modules
use strict;
use warnings;
use File::Find;
use Time::Piece;
use MIME::Lite;
use File::Slurp;
use Fcntl qw(:flock);
use Getopt::Long qw(:config no_ignore_case);
## Generic Variables
my $progversion = "1";
my $progrevision = "1";
my $prog_name = "error_alert.pl";
my $help;
my $version;
my $dryrun;
## Main Program Variables
my $dc = 'IN';
chomp($dc);
my $fileDate = localtime->ymd("-");
chomp($fileDate);
my $logDir = "/home/ajoy/alert-dc/testlogs";
my $Date = localtime->ymd("");
my $pattern = "applmgr\.log\.$Date";
chomp($Date);
chomp($pattern);
my $fileCount = 0;
my $dirCount = 0;
my $errorCount = 0;
my $nullCount = 0;
#my $to = 'ajoy.bharath#XXXXXX';
my $to = '123#xyz.com, 345#xyz.com, xyz#abc.com';
my $from = 'no-reply#xyz.com';
my $subject = "Log Alert ($dc)";
my $subDate = localtime->ymd("/");
chomp($subDate);
my $message = "<h2>Log Processing Status of $dc for Date:- $subDate </h2> <br> <h3>Please find the attached file for stats..!</h3>";
my $outFile = "$logDir/applmgr_status_$dc-$fileDate.txt";
## locking multiple instances of this script
open my $lockFile, ">", "$logDir/script.lock" or die $!;
flock $lockFile, LOCK_EX|LOCK_NB or die "Multiple instance not allowed: $!";
print $lockFile "$$";
## Options Sub Routines
sub print_usage() {
print "Usage: $prog_name or $prog_name with options [-v|--version] [-h|--help] [-d|--dryrun]\n";
exit(1);
}
sub print_version() {
print "$prog_name : $progversion.$progrevision\n";
exit(0);
}
sub print_help () {
print "$prog_name : $progversion.$progrevision";
print "\n";
print "Usage: $prog_name or $prog_name with options [-v|--version] [-h|--help] [-d|--dryrun]";
print "\n";
print "$prog_name = process logs and process summary and send mail\n";
print "-v|--version = Version.\n";
print "-h|--help = This screen.\n";
print "-d|--dryrun = process logs and process summary and output to stdout instead of sending mail\n\n";
print "\n";
exit(0);
}
sub dry_run {
open(FILE, ">$logDir/applmgr_status_$dc-$fileDate.txt") or die "Cannot open file";
printf FILE "%3s %20s %30s %40s %50s\n", "Host Name", "Errors", "Log Path", "Log FIle", "Modified Time";
printf FILE "%3s\n", "-" x 150;
find( \&logProcessing, $logDir);
print FILE "\n\nSUMMARY\n";
printf FILE "%3s\n", "-" x 20;
print FILE "Number of Hosts investigated for error: $dirCount\n";
print FILE "Number of LogFiles investigated for error: $fileCount\n";
print FILE "Number of Hosts processed with errors: $errorCount\n";
print FILE "Number of Hosts processed wihout errors: $nullCount\n";
close(FILE);
my $data = read_file($outFile);
print $data;
exit(0);
}
# Main Program starts here
print_usage() if ( ! GetOptions('v|version' => \$version, 'h|help' => \$help, 'd|dryrun' => \$dryrun));
print_help() if ($help);
print_version() if ($version);
dry_run() if ($dryrun);
open(FILE, ">$logDir/applmgr_status_$dc-$fileDate.txt") or die "Cannot open file";
printf FILE "%3s %20s %30s %40s %50s\n", "Host Name", "Errors", "Log Path", "Log FIle", "Modified Time";
printf FILE "%3s\n", "-" x 150;
find( \&logProcessing, $logDir);
print FILE "\n\nSUMMARY\n";
printf FILE "%3s\n", "-" x 20;
print FILE "Number of Podhosts investigated for error: $dirCount\n";
print FILE "Number of LogFiles investigated for error: $fileCount\n";
print FILE "Number of Podhosts harvested with errors: $errorCount\n";
print FILE "Number of Podhosts harvested wihout errors: $nullCount\n";
&alertMessage;
## Main Program Sub Routines
sub logProcessing {
my $logpath = $File::Find::dir;
my $logfile = $_;
if ( $File::Find::name =~m!$logDir/(.*?)/$pattern! and -d $File::Find::dir ) { $dirCount++ };
if ( $File::Find::name =~m!$logDir/(.*?)/$pattern! and -f $File::Find::name ) { $fileCount++ };
if($File::Find::name =~m!$logDir/(.*?)/$pattern! and -f $File::Find::name) {
my $errorsSeen = `grep 'Errno 110' $File::Find::name|uniq`;
if ($errorsSeen ne "") {
$errorCount++;
my $hostname = $1;
my $lastModTime = localtime ( (stat $File::Find::name)[9] );
printf FILE "%3s %20s %50s %30s %50s\n", $hostname, 'Errno 110', $logpath, $logfile, $lastModTime;
} else { $nullCount++ }
}
}
close(FILE);
sub alertMessage {
my $msg = MIME::Lite->new(
From => $from,
To => $to,
Subject => $subject,
Type => 'multipart/mixed'
);
$msg->attach(
Type => 'text/html',
Data => $message
);
$msg->attach(
Type => 'text/html',
Path => $outFile,
Disposition => 'attachment'
);
$msg->send;
}
==========================================================
sample log file - applmgr.log.20170303
2017-03-03 08:35:13 UTC 965 [14385] ERROR upload process failed with: error(110, 'Connection timed out')
error: [Errno 110] Connection timed out
2017-03-03 08:43:43 UTC 913 [20057] ERROR upload process failed with: error(110, 'Connection timed out')
error: [Errno 110] Connection timed out
2017-05-26 08:10:14 UTC 278 [7665] WARNING Failed to check upload result with: Exception('Received error response 400 Bad Request from HTTP server',)
2017-05-26 08:10:14 UTC 288 [7665] ERROR upload process failed with: error(32, 'Broken pipe') error: [Errno 32] Broken pipe
2017-05-26 08:10:14 UTC 278 [7665] WARNING Failed to check upload result with: Exception('Received error response 400 Bad Request from HTTP server',)
2017-05-26 08:10:14 UTC 288 [7665] ERROR upload process failed with: error(32, 'Broken pipe') error: [Errno 32] Broken pipe
2017-05-26 08:10:14 UTC 278 [7665] WARNING Failed to check upload result with: Exception('Received error response 400 Bad Request from HTTP server',)
2017-05-26 08:10:14 UTC 288 [7665] ERROR upload process failed with: error(32, 'Broken pipe') error: [Errno 32] Broken pipe
2017-03-03 08:29:24 UTC 010 [9417] ERROR upload process failed with: error(110, 'Connection timed out')
error: [Errno 110] Connection timed out
Any help in streamlining this for better performance or better logic is much more appreciable. I'm a novice in perl and I appled my logic as it is. My refences were Automating System Administration with perl and questions I've asked and others asked in stack* sites
This script coverts xls to csv ok.
The challenge is that it does not convert blank cell in the xls to blanks in csv file.
Any help is appreciated: UPDATED SCRIPT
#!/usr/bin/perl
use strict;
use Spreadsheet::ParseExcel;
use Text::CSV;
my $sourcename = shift #ARGV or die "invocation: $0 <source file>\n";
my $source_excel = new Spreadsheet::ParseExcel;
my $source_book = $source_excel->Parse($sourcename)
or die "Could not open source Excel file $sourcename: $!";
my $storage_book;
foreach my $source_sheet_number (0 .. $source_book->{SheetCount}-1) {
my $source_sheet = $source_book->{Worksheet}[$source_sheet_number];
print "--------- SHEET:", $source_sheet->{Name}, "\n";
next unless defined $source_sheet->{MaxRow};
next unless $source_sheet->{MinRow} <= $source_sheet->{MaxRow};
next unless defined $source_sheet->{MaxCol};
next unless $source_sheet->{MinCol} <= $source_sheet->{MaxCol};
foreach my $row_index ($source_sheet->{MinRow} .. $source_sheet->{MaxRow}) {
foreach my $col_index ($source_sheet->{MinCol} .. $source_sheet->{MaxCol}) {
my $source_cell = $source_sheet->{Cells}[$row_index][$col_index];
if ($source_cell && $source_cell->Value) {
#print "( $row_index , $col_index ) =>", $source_cell->Value, "\t;";
print $source_cell->Value, ";";
}
else
{
print ";"
}
}
}
}
sample excel
EFG KDD ABS JME
FGO POP JET
converted as:
EFG;KDD;ABS;JME;
FGO;POP;JET;
but it should be:
EFG;KDD;ABS;JME;
FGO;;POP;JET;
You have to check if the value of the cell is initialized, not the cell it self.
Change:
if ($source_cell) {
#print "( $row_index , $col_index ) =>", $source_cell->Value, "\t;";
print $source_cell->Value, ";";
}
To:
if ($source_cell && $source_cell->Value) {
#print "( $row_index , $col_index ) =>", $source_cell->Value, "\t;";
print $source_cell->Value, ";";
} else {
print ";";
}
should work.
UPDATE:
foreach my $row_index ($source_sheet->{MinRow} .. $source_sheet->{MaxRow}) {
foreach my $col_index ($source_sheet->{MinCol} .. $source_sheet->{MaxCol}) {
my $source_cell = $source_sheet->{Cells}[$row_index][$col_index];
if ($source_cell && $source_cell->Value) {
print $source_cell->Value.";";
} else {
print ";";
}
}
print "\n";
}
}
I am having two huge .csv files one is around 8 GB and other is 3.4 GB file size. I want only few values from each line inside that .csv files.
Its taking huge time to modify the data and copy it into new file.
Could anyone help in modifying the code.So that the modification will be completed in a reasonable time.
Below is the lines of code:
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
require "$ENV{'SAI_HOME'}/bin/utils/Logging.pl";
require "$ENV{'SAI_HOME'}/bin/utils/Utilities.pl";
my $date1 = `date '+%d-%m-%Y_%H-%M-%Ss'`;
chomp($date1);
our $LOGPATH = "$ENV{'SAI_HOME'}/logs/SP6migrationcsv_$date1.log";
my $status = 0;
log_info("Refer $LOGPATH log file for more information");
my $csv = Text::CSV->new( { binary => 1, eol => $/, sep_char => ',' } );
my $file1 = $ARGV[0] or die "Please provide Subscriber and Subscription CSV files on the command line\n";
my $file2 = $ARGV[1] or die "Please provide Subscriber and Subscription CSV files on the command line\n";
my $subscriberFile = "";
my $subscriptionFile = "";
if ( ( grep /SUBSCRIBER/i, $file1 ) && ( grep /SUBSCRIPTION/i, $file2 ) ) {
$subscriberFile = $file1;
$subscriptionFile = $file2;
} elsif ( ( grep /SUBSCRIBER/i, $file2 ) && ( grep /SUBSCRIPTION/i, $file1 ) ) {
$subscriptionFile = $file1;
$subscriberFile = $file2;
} else {
log_error("Invalid CSV files input");
exit -1;
}
my $SP6DIR = `dirname $0`;
chomp $SP6DIR;
$SP6DIR = "${SP6DIR}/SP6";
`mkdir -p $SP6DIR` or checkExit( $?, "Unable to carete $SP6DIR directory" );
my $newSubscriberFile = "Subscriber.csv";
my $newSubscriptionFile = "Subscription.csv";
my $subscriptionimsifile = "$SP6DIR/.IMSI_$newSubscriptionFile";
my $subscriberimsifile = "$SP6DIR/.IMSI_$newSubscriberFile";
$newSubscriberFile = "${SP6DIR}/$newSubscriberFile";
$newSubscriptionFile = "${SP6DIR}/$newSubscriptionFile";
`dos2unix $subscriptionFile $subscriberFile 2>/dev/null`
or checkExit( $?, "Unable to perform dos2unix on input files" );
`cut -d "," -f3 $subscriptionFile > $subscriptionimsifile`
or checkExit( $?, "Failed to get IMSI details from $subscriptionFile" );
`cut -d "," -f1 $subscriberFile > $subscriberimsifile`
or checkExit( $?, "Failed to get IMSI details from $subscriberFile" );
my $isSubscriptionHeaderPresesnt = "false";
my $isSubscriberHeaderPresesnt = "false";
$status = system("head -1 $subscriptionimsifile | grep 'IMSI' >>/dev/null");
if ( $status == 0 ) {
$isSubscriptionHeaderPresesnt = "true";
}
$status = system("head -1 $subscriberimsifile | grep 'IMSI' >>/dev/null");
if ( $status == 0 ) {
$isSubscriberHeaderPresesnt = "true";
}
open( my $subscriptionData, '<:encoding(utf8)', $subscriptionFile )
or die "Could not open '$subscriptionFile' $!\n";
open( NEWSUBSCRIBERDATA, "> $newSubscriberFile" ) or die "Could not open '$newSubscriberFile' $!\n";
open( NEWSUBSCRIPTIONDATA, "> $newSubscriptionFile" ) or die "Could not open '$newSubscriptionFile' $!\n";
if ( "$isSubscriptionHeaderPresesnt" eq "true" ) {
my $subscriptionHeader = <$subscriptionData>;
if ( $csv->parse($subscriptionHeader) ) {
my #subscriptionHeaderFields = $csv->fields();
print NEWSUBSCRIPTIONDATA "\"$subscriptionHeaderFields[0]\",\"$subscriptionHeaderFields[2]\",\"$subscriptionHeaderFields[4]\",\"$subscriptionHeaderFields[5]\",\"$subscriptionHeaderFields[6]\",\"$subscriptionHeaderFields[8]\",\"$subscriptionHeaderFields[13]\",\"$subscriptionHeaderFields[14]\",\"$subscriptionHeaderFields[15]\",\"$subscriptionHeaderFields[16]\",\"$subscriptionHeaderFields[17]\",\"$subscriptionHeaderFields[18]\",\"$subscriptionHeaderFields[25]\",\"$subscriptionHeaderFields[26]\",\"$subscriptionHeaderFields[27]\"\n";
print NEWSUBSCRIBERDATA "\"IMSI\",\"IMEI\",\"MSISDN\",\"$subscriptionHeaderFields[21]\",\"$subscriptionHeaderFields[22]\",\"$subscriptionHeaderFields[12]\",\"$subscriptionHeaderFields[9]\",\"$subscriptionHeaderFields[1]\",\"$subscriptionHeaderFields[0]\"\n";
} else {
log_error("Line could not be parsed: $subscriptionHeader\n");
exit 1;
}
} else {
log_only("No header info in subscription file");
}
if ( "$isSubscriptionHeaderPresesnt" eq "false" && "$isSubscriberHeaderPresesnt" eq "true" ) {
print NEWSUBSCRIBERDATA "\"IMSI\",\"IMEI\",\"MSISDN\",\"CUSTOMER_SEGMENTATION\",\"CUST_SUBCATEGORY\",\"SUBS_TYPE\",\"SUBSCRIPTION_PLAN\",\"CONTRACT_IDREF\",\"SUBSCRIPTION_IDREF\"\n";
} else {
log_only("No header info in subscriber file");
}
my $subscriberHeader = "";
my #subscriptionFields = {};
my #subscriberFields = {};
while ( my $eachSubscriptionLine = <$subscriptionData> ) {
chomp $eachSubscriptionLine;
if ( $csv->parse($eachSubscriptionLine) ) {
#subscriptionFields = $csv->fields();
$status = system("grep \"^[\\\"]*${subscriptionFields[2]}[\\\"]*\\\$\" $subscriberimsifile >> /dev/null");
if ( $status == 0 ) {
my $lastMatchedSubscriberdata = `grep "^[\\\"]*${subscriptionFields[2]}[\\\"]*," $subscriberFile | tail -1`;
chomp $lastMatchedSubscriberdata;
if ( $csv->parse($lastMatchedSubscriberdata) ) {
#subscriberFields = $csv->fields();
if ( "${subscriberFields[0]}" eq "${subscriptionFields[2]}" ) {
#log_only("Updating \"#subscriberFields\" subscriber details from subscription data");
print NEWSUBSCRIBERDATA "\"$subscriberFields[0]\",\"$subscriberFields[1]\",\"$subscriptionFields[2]\",\"$subscriptionFields[21]\",\"$subscriptionFields[22]\",\"$subscriptionFields[12]\",\"$subscriptionFields[9]\",\"$subscriptionFields[1]\",\"$subscriptionFields[0]\"\n";
} else {
log_error("Unable to process #subscriberFields record");
exit -1;
}
} else {
log_error("Line could not be parsed: $lastMatchedSubscriberdata\n");
exit 1;
}
} else {
log_only("Adding new subscriber details from subscription : \"#subscriptionFields\"");
print NEWSUBSCRIBERDATA "\"$subscriptionFields[2]\",,\"$subscriptionFields[3]\",\"$subscriptionFields[21]\",\"$subscriptionFields[22]\",\"$subscriptionFields[12]\",\"$subscriptionFields[9]\",\"$subscriptionFields[1]\",\"$subscriptionFields[0]\"\n";
}
print NEWSUBSCRIPTIONDATA "\"$subscriptionFields[0]\",\"$subscriptionFields[2]\",\"$subscriptionFields[4]\",\"$subscriptionFields[5]\",\"$subscriptionFields[6]\",\"$subscriptionFields[8]\",\"$subscriptionFields[13]\",\"$subscriptionFields[14]\",\"$subscriptionFields[15]\",\"$subscriptionFields[16]\",\"$subscriptionFields[17]\",\"$subscriptionFields[18]\",\"$subscriptionFields[25]\",\"$subscriptionFields[26]\",\"$subscriptionFields[27]\"\n";
} else {
log_error("Line could not be parsed: $eachSubscriptionLine\n");
exit 1;
}
}
close(NEWSUBSCRIPTIONDATA);
open( my $subscriberData, '<:encoding(utf8)', $subscriberFile ) || die "Could not open '$subscriberFile' $!\n";
if ( "$isSubscriberHeaderPresesnt" eq "true" ) {
$subscriberHeader = <$subscriberData>;
}
while ( my $eachSubscriberLine = <$subscriberData> ) {
chomp $eachSubscriberLine;
if ( $csv->parse($eachSubscriberLine) ) {
#subscriberFields = $csv->fields();
$status = system("grep \"^[\\\"]*${subscriberFields[0]}[\\\"]*\\\$\" $subscriptionimsifile >>/dev/null");
if ( $status != 0 ) {
log_only(
"Adding back subscriber details, because unable to get IMSI details from subscription file : \"#subscriberFields\""
);
print NEWSUBSCRIBERDATA "\"$subscriberFields[0]\",\"$subscriberFields[1]\",\"$subscriberFields[2]\",\"$subscriberFields[6]\",,\"$subscriberFields[7]\",,,\n";
}
} else {
log_error("Line could not be parsed: $eachSubscriberLine\n");
exit 1;
}
}
close(NEWSUBSCRIBERDATA);
`sed -i -e '1 s|SUBSCRIPTION_ID|SUBSCRIPTION_IDREF|g' -e '1 s|SUBS_CATEGORY|SUBSCRIPTION_PLAN|g' -e '1 s|SUBS_STATE|SUBS_TYPE|g' -e '1 s|CUST_CATEGORY|CUSTOMER_SEGMENTATION|g' $newSubscriberFile`
or checkExit( $?, "Unable to update header info in subscriber fi le" );
General advice:
Don't use backticks to parse your input. Perl is perfectly capable of doing this with a while loop and split.
Misspelling variable names is going to screw you. Don't. isSubscriptionHeaderPresesnt
mixing your open calls - 3 argument with lexicals is generally preferred, but mismatching isn't nice.
Using the text string "false" in lieu of a boolean is horrible. Don't do it. Someone someday is going to do the equivalent of print "true" if "false" and it's going to break.
The most 'expensive' operation your script will be doing is reading the files. That's almost always true. So find something other than syscalls to grep or sed require full-rereading of the files you're targeting. Assuming subscriptionFile and subscriberFile are your biggies, you're reading them multiple times - you're running a cut that reads the whole thing. A dos2unix that reads the whole thing. A grep that reads the whole thing. And then you're opening it, and reading the whole thing.
your last line is a sed which will... re-read your output file, entirely, and apply a line by line transform to it.
I'm trying to find a match in a multi-line string using this script.
It works only when there's one row in the destination file.
I would like to know if there's any substitution for $_ in order to search a multi-line text?
#!/usr/bin/perl
my $time=`date +%D_%H:%M`;
chomp($time);
my $last_location=`cat /file.txt`;
chomp($last_location);
open (ERRORLOG, ">>/errors.log") || die "failed to open errorlog file \n$!\n\a";
open (MESSAGES, "</logfile") || die "failed to open alarms file \n$!\n\a";
seek(MESSAGES, 0, 2) || die "Couldn't seek to pos: 0 at end of file $!\n";
$end_position = tell(MESSAGES);
if ($end_position < $last_location) {
$last_location=0;
}
if ($end_position > $last_location) {
seek(MESSAGES, $last_location, 0) || die "Couldn't seek to pos: $last_location $! \n";
$num_of_messages_sent=0;
while (<MESSAGES>) {
chomp;
$line_to_check $_;
if ($line_to_check =~ /some text/ ) {
print ERRORLOG "$time: $line_to_check \n";
if ($num_of_messages_sent < 4) {
do something;
}
if ($num_of_messages_sent == 4) {
do something;
}
#increase counter
$num_of_messages_sent = $num_of_messages_sent + 1;
}
}
$last_location = tell(MESSAGES);
# print "last: $last_location , end: $end_position \n";
`echo $last_location >/file_last_location.txt`;
}
close (ERRORLOG);
close (MESSAGES);
Looks better this way:
while (my $line = <MESSAGES>) {
chomp($line);
print "line : $line\n";
if ($line =~ m!your_regexp_here!i){
print ERRORLOG "$time: $line_to_check \n";
$num_of_messages_sent++;
print "\tMATCH\tline: $line\n";
if ($num_of_messages_sent < 4){
print "Found $num_of_messages_sent matches\n";
}
}
}
I am creating a structure from the data below which will be in a text file
BO_ 82 Sim_Tracker_Objects3: 8
SG_ CAN_Trk_Obj_Sim_Enable : 60|4#1+ (1,0) [0|1]
SG_ CAN_Trk_Obj_Curvi_Long_Vel : 32|12#1+ (0.1,-200) [-200|200]
SG_ CAN_Trk_Obj_Curvi_Lat_Vel : 48|12#1+ (0.1,-200) [-200|200]
SG_ CAN_Trk_Obj_Curvi_Long_Posn : 0|16#1+ (0.01,-200) [-200|200]
SG_ CAN_Trk_Obj_Curvi_Lat_Posn : 16|16#1+ (0.01,-200) [-200|200]
The Perl script I am using to generate structure is as below
but I want it to be structure padded; how can I do it?
open (DBC, "test.txt")|| die "cant open dbc $!";
#test = <test>;
close (DBC);
open(OUTFILE1,">typedef.h") || die "cannot open typedef.h\n";
$line_test =$#test;
$delimiter=0;
foreach $line(#test)
{
if($line =~/^BO_ /)
{
if($delimiter gt 0)
{
print OUTFILE1 "}#my_string\n";
}
$delimiter=1;
#dum_struct_name = split(":",$line);
if($dum_struct_name[0]=~/BO_ /)
{
#dum_struct_var = split(" ",$line);
#my_string = $dum_struct_var[2];
my $my_struct = chop(#my_string[0]);
print OUTFILE1 "\n typedef struct\t";
#print OUTFILE1 "#my_string\n";
print OUTFILE1 "{\n";
}
}
if($line =~/^ SG_ /)
{
#dum_var_name = split(":",$line);
if($dum_var_name[0]=~/^ SG_ /)
{
#dum_struct_var_sub = split(" ",$line);
#my_string_sub = $dum_struct_var_sub[1];
#dum_padd_var = split("SG_",#dum_var_name[1]);
print OUTFILE "\n";
#dum_padd_var1=split("#",#dum_padd_var[0]);
#padd_size=split(" ",#dum_padd_var1[0]);
#size=split('\|',#padd_size[0]);
#bit_position=split('\|',#padd_size[1]);
print OUTFILE "bit_size #size[1]\n";
print OUTFILE "bit_position #size[0]\n";
print OUTFILE1 "\tcanbittype\t";
print OUTFILE1 "#my_string_sub[0]:";
print OUTFILE1 " #size[1];\n";
}
}
} print OUTFILE1 "}";
print OUTFILE1 "#my_string\n";
close(OUTFILE1);
The generated file is something like this:
typedef struct {
canbittype CAN_Trk_Obj_Sim_Enable: 4;
canbittype CAN_Trk_Obj_Vcs_Lat_Vel: 12;
canbittype CAN_Trk_Obj_Vcs_Long_Vel: 12;
canbittype CAN_Trk_Obj_Vcs_Lat_Posn: 16;
canbittype CAN_Trk_Obj_Vcs_Long_Posn: 16;
} Sim_Tracker_Objects3;
Use Convert::Binary::C or roll out your own unpack pattern.