Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Need advice (module) to parse nested IF/ELSIF..

by l3nz (Friar)
on Jan 28, 2004 at 18:05 UTC ( #324721=note: print w/replies, xml ) Need Help??


in reply to Need advice (module) to parse nested IF/ELSIF..

This is more a joke than a real solution, still might be useful. This builds a Perl routine via eval and then calls it from the content of your own page. It works more or less like a JSP compiler, turning the page data into native source code, and then compiling it via eval. If you add a thin layer of error control, this might be a viable solution.

The routine it creates expects a hash containing true/false values (the same you will test in your page) and returns a string with the results.

my $code = ""; my %H; while (<DATA>) { chomp; if ( /<%\s*if (.+?)\s*%>/i ) { $code .= " if (\$H{$1}) { \n"; } elsif ( /<%\s*elsif (.+?)\s*%>/i ) { $code .= "} elsif (\$H{$1}) { \n"; } elsif ( /<%\s*else\s*%>/i ) { $code .= "} else { \n "; } elsif ( /<%\s*endif\s*%>/i ) { $code .= "};\n "; } else { $code .= " \$r .= \"$_\";\n"; } } $code = "sub page_expr\n {\n my (%H) = \@_; my \$r = '';\n $code\n; re +turn \$r }; "; eval $code; $H{boys} = 1; $H{nice_boys} = 1; print page_expr( %H ); __DATA__ <%IF boys %> &nbspYou can play football for the whole day. <%IF nice_boys %> &nbspYou don't need to get permission from your teacher. <%ELSIF agreesive_boys%> &nbspPlease respect others <%ELSE%> &nbspPlease talk to me first <%ENDIF%> <%ELSIF girls%> &nbspI suggest you to go to library <%ELSE%> &nbspStay here <%ENDIF%>
This creates dynamically this code (I reformatted it a bit just to make it more readable):
sub page_expr {
 my (%H) = @_; my $r = '';
  if ($H{boys}) {
    $r .= "   You can play football for the whole day.";
    if ($H{nice_boys}) {
      $r .= "     You don't need to get .";
    } elsif ($H{agreesive_boys}) {
      $r .= "     Please respect others";
    } else {
      $r .= "     Please talk to me first";
    };
  } elsif ($H{girls}) {
   $r .= "   I suggest you to go to library";
  } else {
   $r .= "   Stay here";
  };
  return $r;
};
When run, this program prints:
   You can play football for the whole day.    
   You don't need to get permission from your teacher.

Just my euro 0.02. Hope it helps.




Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://324721]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2022-08-15 03:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?