【问题标题】:Why doesn't this Perl array sort work?为什么这个 Perl 数组排序不起作用?
【发布时间】:2011-02-18 16:55:57
【问题描述】:

为什么数组不排序?

代码

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

【问题讨论】:

  • 您希望输出是什么?

标签: perl arrays sorting


【解决方案1】:
@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 组装在一个循环中,并在循环外执行排序操作。

【讨论】:

    【解决方案2】:
    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,因为您在循环中包含设置$count(对我来说)暗示您在寻找可用公寓的数量,而不是列表的数量。如果我错了,就把它改回@data。

    【讨论】:

      【解决方案3】:

      “不起作用”迫使我们读懂您的想法并猜测什么可能起作用。下次,请根据您的预期或期望行为描述问题。

      我的猜测是,您需要排序后的城市列表,其中包含可供共享的公寓房源。如果您想从列表中删除重复项(,您需要列表的唯一元素),请将这些项用作哈希键。

      我会这样写:

      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 个城市:
        - 约翰斯顿
        - 普罗维登斯

      【讨论】:

        猜你喜欢
        • 2014-08-05
        • 2016-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-23
        • 2012-01-18
        相关资源
        最近更新 更多