Skip to content

Instantly share code, notes, and snippets.

@dgunay
Last active April 7, 2019 02:14
Show Gist options
  • Save dgunay/1e88a5bcfa9e0b294d30d98f2e46bdd7 to your computer and use it in GitHub Desktop.
Save dgunay/1e88a5bcfa9e0b294d30d98f2e46bdd7 to your computer and use it in GitHub Desktop.
Perl script that will budget a given dollar amount for after-expenses-and-retirement uses.
@echo off
perl %~dp0\budget %*
#!/usr/bin/env perl
# Given x dollars, how would you like to apportion it into
# savings/investments/retirement/fun?
use strict;
use warnings;
use List::Util qw( sum );
my %portions = (
'savings' => 0.1,
'play money' => 0.3,
'safe investments' => 0.35,
'fun' => 0.25,
);
my $sum = sum values %portions;
die "Portions must total <= 1.0\n" unless $sum <= 1.0;
my $remainder = 1.0 - $sum;
my $amount = $ARGV[0] or die "Please provide a dollar amount to portion out\n";
# get longest of categories to horizontally align dollar amounts in print_category
my $longest = 0;
foreach my $cat (keys %portions) {
$longest = length $cat if length $cat > $longest;
}
# sort into array of hashrefs, descending order by dollars allocated to that category
my @totals = sort { $$b{'allocated'} <=> $$a{'allocated'} } map { {
'category' => $_,
'allocated' => $amount * $portions{$_}
} } keys %portions;
# Print them out
foreach my $hashref (@totals) {
print_category($$hashref{'category'}, $$hashref{'allocated'});
}
# Prints a category
sub print_category {
my $category = shift;
my $allocated = shift;
die 'argument undef' unless defined $category;
die 'argument undef' unless defined $allocated;
print "$category:";
print ' ' for length $category .. $longest;
printf("\$%.2f\n", $allocated);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment