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
True laziness is hard work

In reply to Re: Inventory List Sorting Question by GrandFather
in thread Inventory List Sorting Question by fufaso

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.