http://www.perlmonks.org?node_id=782485


in reply to Problem with push() Function

To common methods.

Group and peek at previous:

my @country_states; for (@logfiles) { my $country_state = $_; # Avoid clobbering @logfiles $country_state =~ s/.txt//; $country_state =~ s/_/ /g; push @country_states, $country_state; } @country_states = sort @country_states; my $last_country; for my $country_state (@country_states) { my ($country, $state) = split(/-/, $country_state, 2); if (!defined($last_country) || $last_country ne $country) { $last_country = $country; print(uc($country), "\n"); } print($state, "\n"); }

Group into a multi-dimensional structure:

my %states_by_country; for (@logfiles) { my $country_state = $_; # Avoid clobbering @logfiles $country_state =~ s/.txt//; $country_state =~ s/_/ /g; my ($country, $state) = split(/-/, $country_state, 2); push @{ $states_by_country{$country} }, $state; } for my $country (sort keys %states_by_country) { print(uc($country), "\n"); my $states = $states_by_country{$country}; for my $state (sort @$states) { print($state, "\n"); } }