Have fun! you are on your way with several ideas that produce correct results. All will run WAY fast enough for your application.
The requirements for this app seem to be a moving target. I thought I'd demo a completely different approach for you. I'm not recommending this for your current requirements, but sounds like something may pop up soon that might need this. This shows "hey, 15 is the "best" one, but what is second best one", etc. This uses the very powerful sort functions of Perl.#!/usr/bin/perl -w use strict; my $ranking_string = "32,15,4,72,13,28,14"; my @ranking = split (/,/, $ranking_string); my $i =1; my %ranking_hash = map {$_ => $i++} @ranking; my $default_best_num = (@ranking)[-1]; while (my $list = <DATA>) { chomp $list; my $best_num = $default_best_num; foreach my $num (split /,/, $list) { next unless $ranking_hash{$num}; $best_num = $num if $ranking_hash{$num} < $ranking_hash{$best_num +}; } print "$best_num\n"; } #prints: #15 #15 #14 __DATA__ 4,13,15 4,50,15,13 50,60,70
#!/usr/bin/perl -w use strict; my $ranking_string = "32,15,4,72,13,28,14"; my @ranking = split (/,/, $ranking_string); my $i =1; my %ranking_hash = map {$_ => $i++} @ranking; my $default_best_num = (@ranking)[-1]; while (my $line = <DATA>) { chomp $line; my @ranking = sort by_min_ranking grep {$ranking_hash{$_}} (split /,/, $line); if (@ranking){print "@ranking - first one is \"best\"\n"} else {print "$default_best_num - default used\n"} } sub by_min_ranking { $ranking_hash{$a} <=> $ranking_hash{$b} } #prints: #15 4 13 - first one is "best" #15 4 13 - first one is "best" #14 - default used
In reply to Re^7: Convert a string into a hash
by Marshall
in thread Convert a string into a hash
by vitoco
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |