in reply to save regex in a file?

Use qr//:
$re = qr/abc(def|ghi)(?:jkl)+/i; open RE, "> my_re.pl" or die "can't write to my_re.pl: $!"; print RE $re; close RE; # later open RE, "< my_re.pl" or die "can't read my_re.pl: $!"; chomp($re = <RE>); close RE;

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Replies are listed 'Best First'.
Re: Re: save regex in a file?
by Hofmator (Curate) on Oct 16, 2001 at 15:16 UTC

    A slightly different approach using the same idea is to put the qr// statements directly in the file and eval them after reading in. This improves the readability if the file is to be edited by human beings.

    So the regex data file would look like this:

    qr/abc/i qr/^\d+$/m ...
    Reading in and evaling (of course this might introduce some security problems) could then be done this way:
    my @regexes; # read in open RE, "< my_re.pl" or die "can't read my_re.pl: $!"; while(<RE>) { chomp; push @regexes, eval; } close RE; # and do the matching for my $re (@regexes) { if ($text =~ $re) { # do something } }

    With some extra effort one could even allow multiline regexes in the data file.

    -- Hofmator