Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^3: Putting the stringified Regexp object into code

by roboticus (Canon)
on Nov 06, 2012 at 20:44 UTC ( #1002576=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Putting the stringified Regexp object into code
in thread Putting the stringified Regexp object into code

sedusedan:

The reason kennethk is wondering why you're avoiding closures is that much template-generated code can be easily replaced with a closure. Generally a string eval can be replaced with something better.

Munging strings to generate functions is certainly possible, and many have done it. But sometimes it's just easier to generate the function itself. An example (very loosely) based on your sample code:

$ cat t.pl #!/usr/bin/perl use strict; use warnings; # Function to accept only 4 digit numbers my $v_4dig = gen_validator('^\d{4}$'); # Function to accept only 3 digit numbers my $v_3dig = gen_validator('^\d{3}$'); # Function to accept only lower-case alphabetic strings my $v_alpha = gen_validator('^[a-z]+$'); for my $t ('apple', 123, 456, 7890) { print "$t:\t", $v_4dig->($t), "\t", $v_3dig->($t), "\t", $v_alpha- +>($t), "\n"; } sub gen_validator { my $regex = shift; # Create function to validate against current regex return sub { my $data = shift; return 1 if ! defined $data; if (ref $data eq '') { return 1 if $data =~ /$regex/; } return 0; } } $ perl t.pl apple: 0 0 1 123: 0 1 0 456: 0 1 0 7890: 1 0 0

Update: Added the third validator function example, just for variety. Also added a couple of comments.

Update: Re-read thread and properly attributed suggestion.

...roboticus

When your only tool is a hammer, all problems look like your thumb.


Comment on Re^3: Putting the stringified Regexp object into code
Download Code
Re^4: Putting the stringified Regexp object into code
by sedusedan (Monk) on Nov 07, 2012 at 00:11 UTC
    Thanks for the suggestion. However, in this case, I really do want to generate code string, because I want to save the code to disk for embedding it in other code, among other uses. For example in Dist::Zilla::Plugin::Rinci::Validate.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2014-09-19 04:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (129 votes), past polls