You have a lot of options in your approach, here. I humbly offer my somewhat more Perl-ish approach to this problem.
The basis of what I did is to get rid of hard-coded fields and allow you to specify them near the top of the script in @fields, building a regexp to capture them in the header line. I relaxed the usage of the program as well, to allow for specifying a filename on the command line, or, if none is specified, accepting input from STDIN. You can easily change the output format by modifying the final for (sort keys %inv) { ... } loop, and you can change how records are grouped by changing the key() function to suit your tastes. In both cases, I tried to stay with what you had, since I don't know what you want to ultimately do with the data.
use strict;
use warnings;
use 5.12.00;
die "usage: $0 [filename]\n" if (@ARGV > 1);
# Set required fields and determine fixed widths
my @fields = qw/Part Shape Color Size/;
my $re;
$re .= qr/(?<$_>$_\s*)/ for @fields;
my $header = <>;
die "Header must match " . join(' ', @fields) unless ($header =~ /^$re
+$/);
my $expected_len = length($header);
my $tmpl = join(' ', map { "A[".length($+{$_})."]" } @fields);
my %inv; # Inventory; $inv{key(%rec)}
while (<>) {
if (length != $expected_len) {
die sprintf("Got length of %d, expecting %d", length, $expecte
+d_len);
}
my @rec = map { /(.+?)\s*$/ } unpack $tmpl; # Get (trimmed) record
+s
my %rec = map { $_ => shift @rec } @fields;
# Add the part to our inventory
push @{$inv{key(%rec)}}, $rec{Part};
}
# Now print out the inventory in the desired format
for (sort keys %inv) {
say join(' ',@{$inv{$_}}) . " - $_ - " . scalar @{$inv{$_}};
}
# Our custom hashing function for inventory items. Expects %rec argume
+nt
sub key { my %rec = @_; $rec{Shape} . $rec{Color} . $rec{Size}; }
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
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.
|
|