decision trees

Randal L. Schwartz merlyn at
Thu Feb 21 13:43:39 CST 2002

>>>>> "Kari" == Kari Chisholm <karic at> writes:

Kari> I found this interesting perl implementation on the net:


Kari> Naturally, there are all kinds of big ugly ways to go about building
Kari> something like this - but it seems that it's recursive nature might
Kari> make it a simple little routine.  Any general ideas?

Yeah, at its heart, it's the game "Animal".  Here's a sample
implementation, which I wrote for a magazine column but haven't
used yet:

    #!/usr/bin/perl -w
    use strict;

    use Data::Dumper;

    my $info = "dog";

      redo if (yes("play again?"));
    print "Bye!\n";
    print Dumper($info);

    sub try {
      my $this = $_[0];
      if (ref $this) {
        return try($this->{yes($this->{Question}) ? 'Yes' : 'No' });
      if (yes("Is it a $this")) {
        print "I got it!\n";
        return 1;
      print "no!?  What was it then? ";
      chomp(my $new = <STDIN>);
      print "And a question that distinguishes a $this from a $new would be? ";
      chomp(my $question = <STDIN>);
      my $yes = yes("And for a $new, the answer would be...");
      $_[0] = {
               Question => $question,
               Yes => $yes ? $new : $this,
               No => $yes ? $this : $new,
      return 0;

    sub yes {
      print "@_ (yes/no)?";
      <STDIN> =~ /^y/i;

Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at> <URL:>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See for onsite and open-enrollment Perl training!

More information about the Pdx-pm-list mailing list