Skip to content

Instantly share code, notes, and snippets.

@squentin
Created February 8, 2012 17:19
Show Gist options
  • Save squentin/1771336 to your computer and use it in GitHub Desktop.
Save squentin/1771336 to your computer and use it in GitHub Desktop.
#returns a function, that function takes a listref of IDs as argument, and returns a hashref of groupid=>score
#returns nothing on error
sub Random::MakeGroupScoreFunction
{ my ($self,$field)=@_;
my ($keycode,$multi)= Songs::LookupCode($field, 'hash','hashm', [ID => '$_']);
unless ($keycode || $multi) { warn "MakeGroupScoreFunction error : can't find code for field $field\n"; return } #return dummy sub ?
($keycode,my $keyafter)= split / +---- +/,$keycode||$multi,2;
if ($keyafter) { warn "MakeGroupScoreFunction with field $field is not supported yet\n"; return } #return dummy sub ?
my ($before,$score)=$self->make;
my $calcIDscore= $multi ? 'my $IDscore='.$score.'; for my $key ('.$keycode.') {$score{$key}+=$IDscore}' : "\$score\{$keycode}+=$score;";
my $code= $before.'; sub { my %score; for (@{$_[0]}) { '.$calcIDscore.' } return \%score; }';
my $sub=eval $code;
if ($@) { warn "Error in eval '$code' :\n$@"; return }
return $sub;
}
__END__
example of use :
my $field='album';
#create function
my $sub=$::RandomMode->MakeGroupScoreFunction($field);
#create hash filled with songs from playlist
my $h=$sub->($::ListPlay);
# show 10 results from hash
for ((keys %$h)[1..10]) {warn Songs::Gid_to_Display($field,$_)." : $h->{$_}\n"; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment