in reply to Re^6: Convert a string into a hash
in thread Convert a string into a hash

There is nothing wrong with either approach. A few comments:
- I would forget about do{}, seldom is that needed in code like this. If there is some need to restrict the scope of my $i, that points to some other problem in the overall code.
- I would use slice (@ranking)[-1] instead of using something like $ranking[$#ranking].
- I started $i at 1 to avoid any ambiguity about undef vs zero value.

Have fun! you are on your way with several ideas that produce correct results. All will run WAY fast enough for your application.

#!/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
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 $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