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

I'm trying to assign a variable a regex, then pass the varibale to a subroutine, then use the passed regex in the subroutine to find a value in a line of text and then return that value. I've tried quotes, single quotes, using quotes around the passed variable in the sub, not using quotes. I've found that since there are spaces in the string I'm searching I have to use to 2 escapes because 1 of the escapes gets stripped. Here's what it looks like:
$val1 = 'Torque\\sDriver\\sCS\#:\\s*(\\D{2}\\d{4})'; $tq = &val_search($val1);
and then in the sub:
sub val_search { my $ret_val = 0; { ($ret_val) = ($line =~ /$_[0]/); print "ret_val = ", $ret_val, "\n"; return $ret_val; } }
I've tried every combination I can think of, does anyone have an idea of how to properly do this?

Replies are listed 'Best First'.
Re: passing a regex to a sub
by dominic01 (Sexton) on Nov 11, 2011 at 17:25 UTC
    Works for me
    $val1 = qr/Torque\sDriver/i; $tq = &val_search($val1); sub val_search { my $line = "abcd Torque Driver efgh"; my $ret_val = 0; { ($ret_val) = ($line =~ /$_[0]/); print "ret_val = ", $ret_val, "\n"; return $ret_val; } }
Re: passing a regex to a sub
by Praethen (Scribe) on Nov 12, 2011 at 02:47 UTC

    Are you getting a script error or just unexpected results?

Re: passing a regex to a sub
by wol (Hermit) on Nov 15, 2011 at 10:11 UTC
    I think you just need to change the way the regex is quoted. Instead of using single quotes, try qr{}. Double quotes should also work.

    Not had a chance to test this alas, but that's what I understand from my little book.

    use JAPH;
    print JAPH::asString();