#!/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_ref; 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; }