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}; }
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.