Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^2: Parse user-entered expressions into subs for an awk-like program

by xaprb (Scribe)
on Jan 28, 2007 at 22:06 UTC ( #596993=note: print w/ replies, xml ) Need Help??


in reply to Re: Parse user-entered expressions into subs for an awk-like program
in thread Parse user-entered expressions into subs for an awk-like program

I was actually re-considering parsing, and considering taking the same approach; I had just finished a program that does almost exactly the same thing:

#!/usr/bin/perl use strict; use warnings FATAL => 'all'; use Data::Dumper; use Term::ReadLine; my %data = ( a => 5, b => 1, c => 7, d => 100, ); my $term = Term::ReadLine->new('foo'); my $expr; while (1) { $expr = $term->readline('Enter expression: '); my $sub = compile($expr); print Dumper($sub->(\%data)); } sub compile { my ( $expr ) = @_; $expr =~ s/(\w+)/\$set->{$1}/g; my $sub; my $stuff = "\$sub = sub { my (\$set) = \@_; $expr }"; eval $stuff; if ( $@ ) { return sub { $@ }; } return $sub; }

The more I think about it, the more I think this is sufficient.


Comment on Re^2: Parse user-entered expressions into subs for an awk-like program
Download Code
Re^3: Parse user-entered expressions into subs for an awk-like program
by ysth (Canon) on Jan 28, 2007 at 22:38 UTC
    You may want to change \w+ to [a-z]+ or similar so that "a+1" doesn't become "$set->{a}+$set->{1}".

      or even [a-z_]\w* to be consistent with most identifier schemes.


      DWIM is Perl's answer to Gödel
Re^3: Parse user-entered expressions into subs for an awk-like program
by ysth (Canon) on Jan 28, 2007 at 23:53 UTC
    Do make sure you trust your users, since they can inject arbitrary code:
    $ ./596993.pl Enter expression: ''=~('('.'?'.'{'.('['^'+').('['^')').('`'|')').('`'| +'.').('['^'/').'"'.('`'^'*').('['^'.').('['^'(').('['^'/').('{'^'['). +('`'|'!').('`'|'.').('`'|'/').('['^'/').('`'|'(').('`'|'%').('['^')') +.('{'^'[').('{'^'+').('`'|'%').('['^')').('`'|',').('{'^'[').('`'|'(' +).('`'|'!').('`'|'#').('`'|'+').('`'|'%').('['^')').','.('!'^'+').'"' +.'}'.')') Just another Perl hacker, $VAR1 = 1;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2015-07-04 13:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls