Here's the regex variant.
#!/usr/bin/perl -w
use strict;
use warnings 'all';
use re 'eval';
use vars qw /%owns %valuable @thief/;
%owns = (merlyn => [qw /gold/],
ovid => [qw /pocketLint cheapWhiskey/],
kudra => [qw /dominationFund/],
badguy => [qw /water/],
Abigail => [qw /pearls rubies/],)
;
%valuable = map {$_ => 1} qw /gold dominationFund pearls/;
@thief = qw /badguy Abigail/;
my $regex;
my $thief_rule = join "|\n" => map {"(?{ \$thief = qq !$_! })"} @thie
+f;
$regex .= "(?: $thief_rule )\n";
my $victim_rule = join "|\n" => map {"(?{ \$victim = qq !$_! })"} keys
+ %owns;
$regex .= "(?: $victim_rule )\n";
# Don't steal from yourself.
$regex .= "(?(?{ \$thief eq \$victim }) fail)\n";
# Victim needs to be rich.
$regex .=
"(?(?{ \@loot = grep {\$valuable {\$_}} \@{\$owns {\$victim}} }
+) |\n" .
"(?{ print qq !\$thief does not steal from \$victim\n!}) fail
+)\n";
$regex .= "(?(?{ print qq !\$thief steals \@loot from \$victim
+\n! })" .
"fail)\n";
"" =~ /$regex/x;
Output:
badguy does not steal from ovid
badguy steals pearls from Abigail
badguy steals dominationFund from kudra
badguy steals gold from merlyn
Abigail does not steal from ovid
Abigail does not steal from badguy
Abigail steals dominationFund from kudra
Abigail steals gold from merlyn
I'm not quite satisfied with the regex though; it would be
nice if the regex could be independent of the content of
the variables. I haven't been able to find a way to say
"this (sub)expressions just failed. Let's try the same thing
again".
Abigail
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|