views:

117

answers:

3

Why won't the array sort?

CODE

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";  

OUTPUT

Providence
Johnston
Johnston
Johnston
6

+6  A: 
@city = "\u\L$fields[1]";  
@city_sort = sort (@city);  

The first line creates a list called @city that has one element. The second line sorts the list (which has one element). There isn't any actual sorting going on in this program.

If I can guess what you are trying to do, you want something more like

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";

This assembles the list @city in a loop, and performs the sort operation outside the loop.

mobrule
A: 
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"; 

I did $count on @city_sort because you inclusion of setting $count in the loop implied (to me) that you were after the number of apartments available, not the number of listings. Just change it back to @data if I'm wrong.

HerbN
A: 

“Doesn’t work” forces us to read your mind and guess what might work. Next time, please describe the problem in terms of your expected or desired behavior.

My guess is you want the sorted list of cities that have listings for apartments to share. When you want to get rid of repeated items from a list (i.e., you want the list's unique elements), use the items as hash keys.

I'd write it this way:

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;

Output:

2 cities:
  - Johnston
  - Providence
Greg Bacon