Universität Ulm, Fakultät für Mathematik und Wirtschaftswissenschaften, SAI

Lösung zu Blatt 5 --- Software Engineering Praxis (SS 2002)

Was mag ich denn?

#!/usr/local/bin/perl -Tw

use strict;
use IO::Dir;
use IO::File;
use CGI;

my %functions = (password => "password_field", select => "scrolling_list",
   radio_group => "radio_group", textfield => "textfield");

my %dir = ();
tie %dir, "IO::Dir", "/tmp/fragen/";
my @questions = ();
my ($file, $fh);
foreach (keys %dir) {
   $file = "/tmp/fragen/" . $_;
   next unless -f $file && -r $file && -T $file && (! -l $file);
   my $fh = new IO::File $file;
   next unless defined $fh;
   my ($question, $kind, $sol, @rest) = ("", "", "", ());
   chomp(($question, $kind, $sol, @rest) = <$fh>);
   close $fh;
   next unless defined $sol && defined $functions{$kind};
   push @questions, { quest => $question, kind => $kind, sol => $sol,
      answers => [sort {$a cmp $b} ($sol, @rest)] };
}
untie %dir;
my $q = new CGI;
print $q->header, $q->start_html("Riddles on the Web"),
   $q->h1("Riddles on the Web");
if ($q->param()) { # the form has already been filled out
   my $solution = $q->param("sol");
   my $guess = $q->param("guess");
   if ($solution eq $guess and defined $solution) {
      print $q->p("Your answer was correct. Very Good :-)\n");
   } else { 
      print $q->p("Sorry, your answer was wrong. Your should have guessed ".
      $q->escapeHTML($solution) . " :-(\n");
   }
}
my %riddle = %{$questions[int(rand(scalar(@questions)))]};
my $tocall = $functions{$riddle{kind}};
print $q->start_form();
print $q->p($q->escapeHTML($riddle{quest}));
my @param = (-name => 'guess', -override => 1);
if ($tocall =~ /(list)|(radio)/) {
   push @param, "values"=> \@{$riddle{answers}};
}
print $q->p($q->$tocall(@param));
print $q->hidden(-name => "sol", -default => [$riddle{sol}], -override => 1);
print $q->submit(), $q->end_form(), $q->hr(), "Ingo Melzer",  $q->end_html;

Universität Fakultät SAI

Ingo Melzer, 30. Mai 2002