I’m looking for help sorting an array where each element is made up of “a number, then a string, then a number”. I would like to sort on the first number part of the array elements, descending (so that I list the higher numbers first), while also listing the text etc.
am still a beginner so alternatives to the below are also welcome
use strict;
use warnings;
my @arr = map {int( rand(49) + 1) } ( 1..100 ); # build an array of 100 random numbers between 1 and 49
my @count2;
foreach my $i (1..49) {
my @count = join(',', @arr) =~ m/$i,/g; # maybe try to make a string only once then search trough it... ???
my $count1 = scalar(@count); # I want this $count1 to be the number of times each of the numbers($i) was found within the string/array.
push(@count2, $count1 ." times for ". $i); # pushing a "number then text and a number / scalar, string, scalar" to an array.
}
#for (@count2) {print "$_\n";}
# try to add up all numbers in the first coloum to make sure they == 100
#sort @count2 and print the top 7
@count2 = sort {$b <=> $a} @count2; # try to stop printout of this, or sort on =~ m/^anumber/ ??? or just on the first one or two \d
foreach my $i (0..6) {
print $count2[$i] ."\n"; # seems to be sorted right anyway
}
First, store your data in an array, not in a string:
Then you can easily sort by the first element of each subarray:
And when you print it, construct the string:
See also: http://perldoc.perl.org/perlreftut.html, perlfaq4