Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.87 KB | None | 0 0
  1. #!/usr/bin/perl
  2. # Author: Martin Dahlo
  3. # Used to calculate debts
  4. # Usage: perl skulder.pl <infile> <outfile>
  5. # Ex.
  6. # perl skulder.pl usa2010.txt resultat.txt
  7.  
  8. use strict;
  9. use warnings;
  10.  
  11. # set the exchange rate, e.g 6.14 for usd -> sek, or 1 for no exchange rate
  12. my $multiplicator = 1;
  13.  
  14. # define a usage message
  15. my $usage = "Usage: perl skulder.pl <infile> <outfile>";
  16.  
  17. # get the file names
  18. my $infile = shift or die $usage;
  19. my $outfile = shift or die $usage;
  20.  
  21. # open the file handles
  22. open IN, "<", $infile or die $!;
  23. open OUT, ">", $outfile or die $!;
  24.  
  25. # initialize variables
  26. my %balance;
  27.  
  28. # go through the debt file
  29. while(<IN>){
  30.    
  31.     # only valid rows, e.g no commented rows
  32.     if($_ =~ m/^([\d\.]+)\t(.+)\t(.+)\t(.+)$/){
  33.        
  34.         # save values to make everything more clear..
  35.         my $sum = $1;
  36.         my $creditor = $2;
  37.         my $debtor = $3;
  38.         my $what = $4;
  39.        
  40.  
  41.         # check the number of people involved
  42.         my @credArr = split(/,/,$creditor);  # create an array with all creditors
  43.         my @debtArr = split(/,/,$debtor);  # create an array with all debtors
  44.         my $nCred = $#credArr + 1;  # count number of creditors
  45.         my $nDeb = $#debtArr + 1;  # count the number of debtors
  46.  
  47.         # increase creditors balance
  48.         for(my $i = 0; $i < $nCred; $i++){
  49.             # increase balance with 1/n of the sum
  50.             $balance{$credArr[$i]} += $sum/$nCred;
  51.         }
  52.        
  53.         # decrease debtors balance
  54.         for(my $i = 0; $i < $nDeb; $i++){
  55.             # decrease balance with 1/n of the sum
  56.             $balance{$debtArr[$i]} -= $sum/$nDeb;
  57.         }
  58.     }
  59. }
  60.  
  61. # initialize checksum
  62. my $checksum = 0;
  63.  
  64. # print the results
  65. foreach my $key (sort keys %balance){
  66.     print OUT "$key:\t".$balance{$key}*$multiplicator."\n";
  67.     print "$key:\t".$balance{$key}*$multiplicator."\n";
  68.     $checksum += $balance{$key};
  69. }
  70.  
  71. # should be zero if all is well. Or really really close to zero.. :)
  72. print OUT "Checksum: $checksum\n";
  73. print "Checksum: $checksum\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement