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


in reply to Making a dynamic high scores table

G'day chickenlips,

Here's a solution using Tie::File which allows you to keep track of high scores within and between instances of your program running.

#!/usr/bin/env perl use strict; use warnings; use Tie::File; use constant MAX_HIGH_SCORES_TO_SHOW => 10; my $high_score_data_file = './pm_high_score.dat'; tie my @high_scores, 'Tie::File', $high_score_data_file or die $!; while (1) { print 'Initials (or Return to end): '; chomp (my $initials = <>); last unless length $initials; my $random_score = 1 + int rand 100; print "Random score: $random_score\n"; print "<<<<<<< Before Adding:\n"; display_high_scores(\@high_scores, MAX_HIGH_SCORES_TO_SHOW); add_high_score(\@high_scores, $random_score, $initials); print ">>>>>>> After Adding:\n"; display_high_scores(\@high_scores, MAX_HIGH_SCORES_TO_SHOW); } untie @high_scores; sub add_high_score { my ($high_scores_ref, $score, $name) = @_; my $record = @$high_scores_ref; for (0 .. $#$high_scores_ref) { if ((split /\s+/, $high_scores_ref->[$_])[0] < $score) { $record = $_; last; } } splice @$high_scores_ref, $record, 0, join ' ' => $score, $name; return; } sub display_high_scores { my ($high_scores_ref, $max_to_show) = @_; $max_to_show = MAX_HIGH_SCORES_TO_SHOW unless defined $max_to_show +; $max_to_show = @$high_scores_ref if $max_to_show > @$high_scores_r +ef; my $printf_pattern = "%-5d %s\n"; print "High Score Table\n"; for (0 .. $max_to_show - 1) { printf $printf_pattern => split /\s+/, $high_scores_ref->[$_], + 2; } return; }

Here's a sample run:

$ cat pm_high_score.dat cat: pm_high_score.dat: No such file or directory $ pm_high_score.pl Initials (or Return to end): AA Random score: 82 <<<<<<< Before Adding: High Score Table >>>>>>> After Adding: High Score Table 82 AA Initials (or Return to end): BB Random score: 69 <<<<<<< Before Adding: High Score Table 82 AA >>>>>>> After Adding: High Score Table 82 AA 69 BB Initials (or Return to end): $ cat pm_high_score.dat 82 AA 69 BB ... ran several times to exceed MAX_HIGH_SCORES_TO_SHOW ... High Score Table 90 II 90 LL 85 DD 82 AA 81 EE 69 BB 56 CC 55 GG 39 JJ 23 FF Initials (or Return to end): $ cat pm_high_score.dat 90 II 90 LL 85 DD 82 AA 81 EE 69 BB 56 CC 55 GG 39 JJ 23 FF 22 KK 18 HH 16 MM

-- Ken