Folks I am trying to make an application that will loop over each line in a text file, and format output. However, the first line is dropping the decimal. Looking for some ideas on how to fix this and explain what is going on.
I created my working copy in Python; however, I really want to learn Perl over Python.
#!/usr/bin/perl
#checkbook
#2017-06-20
## This app will create a general ledge
sub format_value {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}
$item_date = "DATE";
$item_description = "DESCRIPTION";
$item_account = "ACCOUNT";
$item_debit = "DEBIT";
$item_credit = "CREDIT";
$item_balance = "BALANCE";
$blank_debit = " ";
$blank_credit = " ";
open (file_read, "input-checkbook.txt");
open (file_write, ">checkbook.txt");
sub runScript {
$main_balance = 0.00;
$format_main_balance = sprintf("%.2f",$main_balance);
while ($line = <file_read>) {
@fields = split /,/, $line;
chomp(@fields);
$date = @fields[0];
$description = @fields[1];
$length_description = length($description);
if ($length_description > 40) {
$description = substr $description, 0, 40;
substr($description,-1) = "~";
} else {
$description = @fields[1];
}
if (@fields[2]){
$debit = @fields[2];
#$debit_decimal = sprintf("%.2f",$debit);
$format_debit = format_value($debit);
$main_balance = $main_balance - $debit;
#sprintf file_write "%s\n", $l_format_main_balance;
$format_main_balance = format_value($main_balance);
#$format_main_balance = sprintf("%.2f",$format_main_balance);
printf file_write "%-11s %-41s %10s %11s %11s\n", @fields[0], $d
+escription, $format_debit, $blank_credit, $format_main_balance;
} else {
$credit = @fields[3];
#$credit = sprintf("%.2f",$credit);
$format_credit = format_value($credit);
$main_balance = $main_balance + $credit;
$format_main_balance = format_value($main_balance);
#$format_main_balance = sprintf("%.2f",$format_main_balance);
printf file_write "%-11s %-41s %10s %11s %11s\n", @fields[0], $d
+escription, $blank_debit, $format_credit, $format_main_balance;
}
}
}
printf file_write "%-11s %-41s %-11s %-11s %-10s\n",$item_date,$item_d
+escription,$item_debit,$item_credit,$item_balance;
printf file_write "===================================================
+=====================================\n";
runScript();
close(file_read);
close(file_write);
exit;
Text file
2017-05-01,starting balance to track character count,,900000.00
2017-05-01,phone bill dsfsdfsfdsfsfsfsdfsfsfsfsfdfsdfsfsfsfsf,300000.0
+0,
2017-05-03,Water,100000.34,
2017-05-05,Electric Bill,900.21,
2017-06-03,debit 45678901dfsf2345678901234567890ddddddddddddd,30.32
2017-06-03,12345678901234567890123456789034,,30.98
2017-06-03,credit 8901234567890123456789034567890123,,30.98
2017-06-03,credit dfdfd01234567890123456789034567890123,,30.98
2017-06-08,Food,23.00,
2017-06-12,Cash,20.00,