Popcorn Dave has asked for the wisdom of the Perl Monks concerning the following question:

Fellow monks,
I have a quandry here that is driving me to the brink.

I'm trying to evaluate a user supplied regex and when I test m/ for some reason it's not returning the $& variable.

Test code follows:

#!/usr/bin/perl $user_text="drab"; $regex='m/ab/'; eval "'drab' =~ $regex"; print "User: $user_text, Reg: $regex\n"; print "Match:$&\n"; my $i = 1; my $var='$'.$i; print "Fine\n" if defined(eval"$var"); while (defined(eval"$var")){ print "Got here too...\n"; my $found=eval"$var"; print "Var $var is $found\n"; $var='$'.++$i; }

I've had close to a tin of Penguin mints tonight trying to debug this one. :)

I've learned quite a lot in the process ( fixed the other errors ), but unfortunately not what I needed to fix this problem.

Any ideas and/or help is greatly appreciated.

Replies are listed 'Best First'.
Re: Problems evaluating a user supplied regex using eval (boo)
by boo_radley (Parson) on Apr 24, 2002 at 06:26 UTC
    this line from perlvar about $& should assist :
    This variable is read-only and dynamically scoped to the current BLOCK


    Guess what an eval counts as?

    This will also affect the $n variables.

    If you plan on matching only, you might take a look at evaling the creation of the regex, something like (off the top of my head) :
    eval ($re=qr/foobar/) || warn $@;
    or
    if (eval ($re=qr/quuzy/)) { # manipulate } else { #blargh! bad re }
      Thanks for the reply!

      So since eval is scoped to it's block, then am I correct in assuming I could do something along the lines of

      eval { $my_text =~$regex # where $regex is m/ab|(cd)/ for example print $&; print $1, $2 # if defined }

      and then $& will hold the value of the match, and $1 and $2 will be accessable?

      My understanding of this, and please correct me if I'm wrong, is that since eval is dynamically scoped, as long as my code is blocked between {} I'm okay.