in reply to Inventory List Sorting Question

#! /usr/bin/env perl use Modern::Perl; use strict; use warnings; use feature qw( say state ); # Perl 5.10.0 or greater my @inventory = split /\R/, "YEAR MAKE MODEL PRICE 2003 abc rel 999 1999 hds sdf 100 2010 kls pol 1400"; my %columns = map { state $c = 0; lc, $c++ } map { split } (my $header = shift @inventory); print "sort by? "; chomp(my $lookfor = lc <STDIN>); die "bad sort criteria" unless exists $columns{$lookfor}; my $sortcol = $columns{$lookfor}; say for $header, sort { if (grep { /\D/ } (split ' ', $a)[$sortcol], (split ' ', $b)[$ +sortcol]) { (split ' ', $a)[$sortcol] cmp (split ' ', $b)[$sortcol] } else { (split ' ', $a)[$sortcol] <=> (split ' ', $b)[$sortcol] } } @inventory;

Replies are listed 'Best First'.
Re^2: Inventory List Sorting Question
by fufaso (Initiate) on Sep 22, 2010 at 23:19 UTC
    I got it sorted, and did something a little different. Is there a benefit to doing it one way over the other? Here's my code:
    $lookfor=<STDIN>; chop($lookfor); if ($lookfor =~ /year/i){ for $list_ref1 ( sort { $a->[0] cmp $b->[0] } @inventory ) { print "\t [ @$list_ref1 ],\n"; } } if ($lookfor =~ /make/i){ for $list_ref1 ( sort { $a->[1] cmp $b->[1] } @inventory ) { print "\t [ @$list_ref1 ],\n"; } }