What gryphon and Trimbach say is, as usual, true. Unfortunately, figuring out precisely what your boss wants is something you'll have to do yourself. Here's an idea on how to make the program more flexible.
First, extract out your parsing subroutine into a separate subroutine that reads a line of your program and returns a hash. (We'll cover that in a second.) So, your reading loop can look like this:
Disclaimer: All code untested.
my @claim_records = (); while (<CLAIMS>) { push(@claim_records, read_record($_)); }
Next, you're going to want to redo your read_record routine to use unpack() and hash references. First, you should define the template for unpack(). I tend to do these things as constants. I won't do the whole thing, just the first three fields for illustration:
'A8A6A2' means "The claim template line will consist of fixed-length strings, the first of whose length is 8, second six, third two". You'll need to add to this template. Ditto the CLAIM_KEYS, which we'll use to access the info later on. I put the CLAIM_KEYS up there next to them, so it's easier to keep them in the same order. Then, you can have read_record do this:## Put this at the top of your program ## This would be much longer in your program. use constant CLAIM_TEMPLATE => 'A8A6A2'; use constant CLAIM_KEYS => qw( claim_batch_number claim_number claim_type );
What this does: first it creates an empty hash, %claim_record. Then it unpacks the fixed-length strings in that line of the template record, and assigns the first record to 'claim_batch_number', the second to 'claim_number', etc. Then it returns a reference to the %claim_record hash to our main routine, where it's stored in an array.sub read_record { my ($line) = @_; my %claim_record = (); @claim_record{ CLAIM_KEYS } = unpack(CLAIM_TEMPLATE, $line); return \%claim_record; }
Now, if you want to sort these guys, you have an easier time. Just remember that you can define your own comparison routine for sort:
my $sort_by = 'claim_type'; foreach $record ( sort sub { $a->{$sort_by} cmp $b->{$sort_by} } @clai +m_records ) { print STDOUT $record->{'claim_number'}, "\n"; }
That way, you can change what you sort on by changing $sort_by.
I haven't had a chance to test this, so corrections are encouraged. Best of luck.
stephen
In reply to Re: Help with arrays/sub procedures
by stephen
in thread Help with arrays/sub procedures
by Prince99
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |