On Feb 20, 2004, at 2:02 PM, Joel wrote:

Thanks, can you give me some examples of loops like that?

Here's one:


#!/usr/bin/perl

use strict;
use warnings;

# build world as nested hashes
my %world = ( Bridge => { Description => 'The Bridge of the spaceship...',
Exits => { North => 'Quarters',
West => 'Airlock',
South => 'Engines' } },
Engines => { Description => 'The ship\'s engine room...',
Exits => { North => 'Bridge' } },
Airlock => { Description => 'The primary airlock...',
Exits => { East => 'Bridge' } },
Quarters => { Description => 'Crew quarters...',
Exits => { South => 'Bridge' } } );
# if would be easy and better to replace the above hard coded definitions,
# with definitions loaded from an external data file


my $where = 'Bridge';   # starting point
while (1) {             # infinite event loop
        # describe where we are
        print "\n$where\n  $world{$where}{Description}\nExits\n";
        for my $exit (keys %{ $world{$where}{Exits} }) {
                print "  $exit ($world{$where}{Exits}{$exit})";
        }
        
        # ask for a command
        print "\n\nWhat now?  ";
        chomp( my $command = <> );

        # parse commands
        if ($command =~ /^(?:n(?:orth)?|e(?:ast)?|s(?:outh)?|w(?:est)?)$/i) {
                my %directions = qw(n North e East s South w West);
                my $exit = $directions{lc substr $command, 0, 1};
                if (exists $world{$where}{Exits}{$exit}) {
                        $where = $world{$where}{Exits}{$exit};  # change location
                }
                else { print "\nYou can't go $exit from here.\n"; }
        }
        elsif ($command =~ /^l(?:ook)?$/i) {
                # DO NOTHING - just looping will reprint description
        }
        elsif ($command =~ /^(?:quit|exit|bye)$/i) { exit; }
        else { print "\nCommand '$command' not found.\n"; }
        # etc...
}

__END__

I like that and it would be easier to do more with it, but it uses references. Are you familiar with those? If not, you might start by feeding your command line 'perldoc perlreftut' and reading the tutorial it brings up.

Good luck.

James


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to