Bodhisattvas,
Here is my current (and working) OOP version of
Versatile subs. As this is my first time dabbling with OOP, I'm looking for feedback.
Thank you.
Module:
#!/usr/bin/perl
package Hasher;
use Carp;
use strict;
use warnings;
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $self = {};
bless ($self, $class);
return $self;
}
sub file {
my $self = shift;
if (@_) {
$self->{file} = shift;
}
}
sub _common {
my $self = shift;
(my $key = (caller(1))[3]) =~ s/.*:://;
if (@_) {
$self->{$key} = shift;
}
else {
$self->{$key}->($self) if defined $self->{$key};
}
}
sub pre {
my $self = shift;
$self->_common(@_);
}
sub loop {
my $self = shift;
$self->_common(@_);
}
sub post {
my $self = shift;
$self->_common(@_);
}
sub hash {
my $self = shift;
croak 'file does not exist' if not -e $self->{file};
$self->{count} = 0;
$self->{hash} = ();
$self->pre();
open my $fh, '<', $self->{file} or croak "could not open $self
+->{file}: $!";
while (my $record = <$fh>) {
chomp $record;
$self->{record} = $record;
$self->loop();
$self->{hash}{ $self->{key} } = $self->{value};
++$self->{count};
}
$self->post();
return %{$self->{hash}};
}
1;
script:
#!/usr/bin/perl
use strict;
use warnings;
use Hasher;
my $states = new Hasher();
$states->file('states');
$states->loop(
sub {
my $self = shift;
($self->{value}, $self->{key}) = split ' ', $self->{re
+cord}, 2;
$self->{key} = uc $self->{key};
}
);
$states->post(
sub {
my $self = shift;
print "hashed $self->{count} states\n";
}
);
my %state = $states->hash();
map {
print "$_ = $state{$_}\n";
} keys %state;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.