为什么数组不排序?
my @data = ('PJ RER Apts to Share|PROVIDENCE',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Condo|WEST WARWICK',
'PJ RER Condo|WARWICK');
foreach my $line (@data) {
$count = @data;
chomp($line);
@fields = split(/\|/,$line);
if ($fields[0] eq "PJ RER Apts to Share"){
@city = "\u\L$fields[1]";
@city_sort = sort (@city);
print "@city_sort","\n";
}
}
print "$count","\n";
普罗维登斯
约翰斯顿
约翰斯顿
约翰斯顿
6
答案 0 :(得分:6)
@city = "\u\L$fields[1]";
@city_sort = sort (@city);
第一行创建一个名为@city
的列表,其中包含一个元素。
第二行对列表进行排序(其中包含一个元素)。这个程序中没有任何实际的排序。
如果我能猜出你想要做什么,你想要更像
的东西my @city = ();
my $count = @data;
foreach my $line (@data) {
@fields = split /\|/, $line;
if ($fields[0] eq "PJ RER Apts to Share") {
push @city, "\u\L$fields[1]";
}
}
@city_sort = sort @city;
print @city_sort, "\n", $count, "\n";
这会在循环中汇编列表@city
,并在循环外执行排序操作。
答案 1 :(得分:0)
my @data = ('PJ RER Apts to Share|PROVIDENCE',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Condo|WEST WARWICK',
'PJ RER Condo|WARWICK');
foreach my $line (@data) {
chomp($line);
@fields = split(/\|/,$line);
if ($fields[0] eq "PJ RER Apts to Share"){
push @city, "\u\L$fields[1]";
}
}
@city_sort = sort (@city);
print map {"$_\n";} @city_sort;
$count = @city_sort;
print "$count","\n";
我对@city_sort进行了计数,因为你在循环中设置$ count隐含(对我而言)你是在可用的公寓数量之后,而不是列出的数量。如果我错了,只需将其改回@data。
答案 2 :(得分:0)
“不起作用”迫使我们阅读你的想法并猜测可能有用的东西。下次,请根据您的预期或期望行为描述问题。
我猜你想要列出公寓列表的城市排序列表。如果要从列表中删除重复项(即。,您需要列表的唯一元素),请将这些项用作哈希键。
我会这样写:
my %aptcities;
foreach my $rec (@data) {
my($type,$city) = split /\|/, $rec;
next unless $type eq "PJ RER Apts to Share";
$city =~ s/(\w+)/\u\L$1/g; # handle WEST WARWICK, for example
++$aptcities{$city};
}
my $n = scalar keys %aptcities;
my $ies = $n == 1 ? "y" : "ies";
print "$n cit$ies:\n",
map " - $_\n", sort keys %aptcities;
输出:
2 cities: - Johnston - Providence