我是perl的新手。假设我有一个包含如下值的数组:
@array = ("2014 Computer Monitor 200", "2010 Keyboard 30", "2012 Keyboard 80", "2011 Study Desk 100");
如何在perl中使用正则表达式按年份,项目名称和价格对整个数组进行排序?例如,如果用户想要按价格排序,则键入“价格”并按如此排序:
2010 Keyboard 30 2012 Keyboard 80 2011 Study Desk 100 2014 Computer Monitor 200
到目前为止,我已经能够像这样按年分类:
@array = ("2014 Computer Monitor 200", "2010 Keyboard 30", "2012 Keyboard 80", "2011 Study Desk 100"); $input = ; chomp($input); if ($input eq "year") { foreach $item (sort {$a cmp $b} @array) { print $item . "\n"; } }
答案 0 :(得分:2)
/(\d+) \s+ (.+) \s+ (\S+)/x
将匹配年份名称和价格,
use strict;
use warnings;
my $order = "price";
my @array = (
"2014 Computer Monitor 200",
"2010 Keyboard 30",
"2012 Keyboard 80",
"2011 Study Desk 100"
);
my %sort_by = (
year => sub { $a->{year} <=> $b->{year} },
price => sub { $a->{price} <=> $b->{price} },
name => sub { $a->{name} cmp $b->{name} },
);
@array = sort {
local ($a, $b) = map {
my %h;
@h{qw(year name price)} = /(\d+) \s+ (.+) \s+ (\S+)/x;
\%h;
} ($a, $b);
$sort_by{$order}->();
} @array;
# S. transform
# @array =
# map { $_->{line} }
# sort { $sort_by{$order}->() }
# map {
# my %h = (line => $_);
# @h{qw(year name price)} = /(\d+) \s+ (.+) \s+ (\S+)/x;
# $h{name} ? \%h : ();
# } @array;
use Data::Dumper; print Dumper \@array;
输出
$VAR1 = [
'2010 Keyboard 30',
'2012 Keyboard 80',
'2011 Study Desk 100',
'2014 Computer Monitor 200'
];
答案 1 :(得分:0)
使用不带变换的排序:
use strict;
use warnings;
my @array = ( "2014 Computer Monitor 200", "2010 Keyboard 30", "2012 Keyboard 80", "2011 Study Desk 100" );
my $order = "price";
my @sorted = sort {
local ( $a, $b ) = map { /^(?<year>\d+) \s+ (?<name>.*) \s (?<price>\d+)/x ? {%+} : die "Can't parse $_" } ( $a, $b );
($order ne 'name' ? $a->{$order} <=> $b->{$order} : 0) || $a->{name} cmp $b->{name}
} @array;
print "$_\n" for @sorted;
输出:
2010 Keyboard 30
2012 Keyboard 80
2011 Study Desk 100
2014 Computer Monitor 200