Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • Mmm, neat! I wanted to get one little bit of syntactic sugar in there, but that made it more complicated than I was hoping:
    use strict;
    use warnings;

    package Calc;

    use base 'Exporter';
    our @EXPORT = qw( income expense monthly );

    sub income {
        my ( $type, $amount ) = @_;
        __PACKAGE__->new( $type, $amount );
    }

    sub expense {
        my ( $type, $amount ) = @_;
        __PACKAGE__->new( $type, -$amount );
    }

    sub monthly {
        my $self = shift;
        $self->{ amt } *= 12;
        return $self;
    }

    sub new {
        my $class = shift;
        my ( $type, $amount ) = @_;

        bless {
            type => $type,
            amt  => $amount,
        }, $class;
    }

    my $total = 0;  # start with a clean balance

    sub DESTROY {
        my $self = shift;
        $total += $self->{ amt };
        my $sign = $self->{ amt } < 0 ? "+" : "-";
        printf "%20s: %s%6d %7d\n", $self->{ type }, $sign, abs( $self->{ amt } ), $total;
    }

    1;
    So after all that mumbojumbo you can now say
    use Calc;

    monthly income 'Yak Milking' => 1000;
    monthly expense Hosting => 100;
    expense PowerBook => 3500;
    # ...
    and you'll get the same output as you had.
    • That's a really good idea. Here's a different approach:

      no strict 'refs';
      sub monthly ($$$) {
          my ($function, $type, $amount) = @_;
          &$function($type, $amount * 12);
      }

      sub quarterly ($$$) {
          my ($function, $type, $amount) = @_;
          &$function($type, $amount * 4);
      }

      sub biweekly ($$$) {
          my ($function, $type, $amount) = @_;
          &$function($type, $amount * 26);
      }

      sub weekly ($$$) {
          my ($function, $type, $amount) = @_;

      • Yuck. I don't think the Schemers have much more appreciation for symrefs than the Perlistas. :-)

        The difference is I wanted to be able to easily throw more qualifiers into the mix:

        sub bi {
            my $self = shift;
            $self->{ amt } /= 2;
            return $self;
        }

        # and later:

        bi monthly expense Whatever => 100;

        It didn't start out OO. Initially I tried to just pass closures up the call chain. That didn't work too well though: I had to check wantarray everywhere to do the printin