Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- # Author: Martin Dahlo
- # Used to calculate debts
- # Usage: perl skulder.pl <infile> <outfile>
- # Ex.
- # perl skulder.pl usa2010.txt resultat.txt
- use strict;
- use warnings;
- # set the exchange rate, e.g 6.14 for usd -> sek, or 1 for no exchange rate
- my $multiplicator = 1;
- # define a usage message
- my $usage = "Usage: perl skulder.pl <infile> <outfile>";
- # get the file names
- my $infile = shift or die $usage;
- my $outfile = shift or die $usage;
- # open the file handles
- open IN, "<", $infile or die $!;
- open OUT, ">", $outfile or die $!;
- # initialize variables
- my %balance;
- # go through the debt file
- while(<IN>){
- # only valid rows, e.g no commented rows
- if($_ =~ m/^([\d\.]+)\t(.+)\t(.+)\t(.+)$/){
- # save values to make everything more clear..
- my $sum = $1;
- my $creditor = $2;
- my $debtor = $3;
- my $what = $4;
- # check the number of people involved
- my @credArr = split(/,/,$creditor); # create an array with all creditors
- my @debtArr = split(/,/,$debtor); # create an array with all debtors
- my $nCred = $#credArr + 1; # count number of creditors
- my $nDeb = $#debtArr + 1; # count the number of debtors
- # increase creditors balance
- for(my $i = 0; $i < $nCred; $i++){
- # increase balance with 1/n of the sum
- $balance{$credArr[$i]} += $sum/$nCred;
- }
- # decrease debtors balance
- for(my $i = 0; $i < $nDeb; $i++){
- # decrease balance with 1/n of the sum
- $balance{$debtArr[$i]} -= $sum/$nDeb;
- }
- }
- }
- # initialize checksum
- my $checksum = 0;
- # print the results
- foreach my $key (sort keys %balance){
- print OUT "$key:\t".$balance{$key}*$multiplicator."\n";
- print "$key:\t".$balance{$key}*$multiplicator."\n";
- $checksum += $balance{$key};
- }
- # should be zero if all is well. Or really really close to zero.. :)
- print OUT "Checksum: $checksum\n";
- print "Checksum: $checksum\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement