As aforementioned, this is getting to be
too much (in perl? never! ...yes!)
What I have now is nearly the same as before; instead of keeping the "limbo" data in $self, it is now in %data which the method declares. I decided against the closure route because it would not work without declaring the variables before the anonymous subs. (Read: I'm trying to make this as easy to use as possible. No required declares on their part, no variable mix-ups, etc.) Is there anything horribly taboo in my methodology or is this decent? I need to get this nailed down soon, and without overcomplication. Thanks!--Here's the new:
Class:
#!/usr/bin/perl
package Hasher;
use Carp;
use strict;
use warnings;
sub new {
my $class = shift;
my $self = { @_ };
bless ($self, $class);
return $self;
}
sub hash {
my $self = shift;
croak 'file does not exist' if not -e $self->{file};
my %data;
$data{count} = 0;
$data{hash} = {};
$self->{pre}->(\%data) if $self->_verify('pre');
open my $fh, '<', $self->{file} or croak "could not open $self
+->{fi
le}: $!";
while (<$fh>) {
chomp;
$data{record} = $_;
$self->{loop}->(\%data) if $self->_verify('loop');
++$data{count};
}
$self->{post}->(\%data) if $self->_verify('post');
return %{$data{hash}};
}
sub _verify {
my $self = shift;
my $key = shift;
return 1 if (
exists $self->{$key} &&
ref($self->{$key}) eq 'CODE'
);
return 0;
}
1;
Script:
#!/usr/bin/perl
use strict;
use warnings;
use Hasher;
my $states = Hasher->new(
file => 'states',
loop => sub {
my $data_ref = shift;
my ($value, $key) = split ' ', $data_ref->{record}, 2;
$data_ref->{hash}->{ uc $key } = $value;
},
post => sub {
my $data_ref = shift;
print "hashed $data_ref->{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.