Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^3: Parse::RandGen::Regexp

by Tanktalus (Canon)
on Aug 07, 2005 at 03:42 UTC ( #481604=note: print w/replies, xml ) Need Help??


in reply to Re^2: Parse::RandGen::Regexp
in thread Parse::RandGen::Regexp

To convert the first string, (?smi)^STOR\s[^\n]{100}, into a compiled regular expression for P::RG::R, just use qr/$string/, assuming $string contained the string as read from the external source (don't forget to chomp it if that's the case!).

To convert the second string, /^STOR\s[^\n]{100}/smi, again, assuming $string is read from an external source (not perl code - perl DATA is fine), just use eval "qr$string".

No matter what, if the string is starting out inside perl code, you have to escape the \'s that have special meaning to the regular expression parser but not to perl, such as \s, \w, \S, \W, \d, \D, ... so that they survive to the parser. This is not needed if the string is stored outside of code because then the perl compiler won't see the \'s.

Replies are listed 'Best First'.
Re^4: Parse::RandGen::Regexp
by paulski (Beadle) on Aug 07, 2005 at 06:37 UTC
    OK that makes sense to me now. :-) I tried this and got it working. I'm not sure what you mean by "stored outside of code" though. Could you please clarify?

    Thanks,

    Paul

      This can mean anywhere that you need to read it from a filehandle, or get it as a return from some other function. For example, you could have it in an actual file. You could put it in a __DATA__ or __END__ block at the end of your file and read it from the *DATA filehandle. You could retrieve it using LWP from a webserver somewhere, then parse it from that. As long as it isn't contained as text inside your actual perl code where the perl compiler will see it.

      Here's an example:


      #!/usr/bin/perl -w use strict; use Parse::RandGen::Regexp; my $regexp = <DATA>; chomp $regexp; # get rid of the line termination. my $r = Parse::RandGen::Regexp->new(qr/$regexp/); my $string = $r->pick(match=>1, captures=>{}); print("\$string: $string\n"); __END__ (?smi)^STOR\s[^\n]{100}

      Here we're loading it from the __END__ section. For more info on how to use the DATA filehandle, see perldata. Otherwise, you can take the string, put it in a file, and then open/read/close that file as normal.

        Shouldn't that be
        (?smi:^STOR\s[^\n]{100})
        Cool thanks. :-)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2021-05-11 00:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Perl 7 will be out ...





    Results (111 votes). Check out past polls.

    Notices?