There are a few things that can be learned here. First off, always use strictures (use strict; use warnings;).
Next, avoid wherever possible handling records using parallel arrays. There are many ways to do that, but in this case I suggest using an array of hashes - you'll see why in a moment.
Where you have named data try to use the name in your code rather than translating it into an index and simply using the index everywhere. It makes it much easier to see what the code is doing!
Don't use chop. Use chomp instead, it's more likely to do what you expect.
Because you want to sort by an arbitrary field in your data it's easiest if you can directly access the fields by name. That implies a hash. The following sample code populates an array of items with records that are hashes containing an entry for each field. Don't spend too much time puzzling over how @items gets populated or @sorted gets printed. The key parts here are the sort and the data structure.
use strict; use warnings; my @items; while (<DATA>) { chomp; my ($year, $make, $model, $price) = split; push @items, {year => $year, make => $make, model => $model, price => $pric +e}; } my $lookFor = lc <STDIN>; chomp $lookFor; die "year, make, model or price expected\n" if $lookFor !~ /^(year|make|model|price)$/; my @sorted = sort {$a->{$lookFor} cmp $b->{$lookFor}} @items; printf "%4s %-6s %-6s %6s\n", @{$_}{qw(year make model price)} for @so +rted; __DATA__ YEAR MAKE MODEL PRICE 2003 abc rel 999 1999 hds sdf 100 2010 kls pol 1400
In reply to Re: Inventory List Sorting Question
by GrandFather
in thread Inventory List Sorting Question
by fufaso
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |