Regex newbie

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I want to use a regex in which the string for which we are searching
is a variable. Is this possible - it doesnt seem to work for me.

$a = "be";

$b="to be or not to be";
if ($b =~ m/$a/i )
print "this should be true";

$b = "apples and oranges";
if ($b =~ m/$a/i )
print "this should be false";


Re: Regex newbie

Quoted text here. Click to load it

Either you have to use post condition or have to close block after if
statement with brackets

print "this should be true" if ($b =~ /$a/i);


if ($b =~ /$a/i){
     print "this should be true";


Re: Regex newbie

gazza67 wrote:
Quoted text here. Click to load it

1) Don't use $a & $b. Quote from 'perldoc perlvar':
    Special package variables when using sort(), see "sort" in
    perlfunc.  Because of this specialness $a and $b don't need to
    be declared (using use vars, or our()) even when using the
    "strict 'vars'" pragma.  Don't lexicalize them with "my $a" or
    "my $b" if you want to be able to use them in the sort() com‐
    parison block or function.

2) You can make a better distinction between matching text and matching
variables by enclosing your variables in curly brackets, eg:
    $string =~ /$/;


Site Timeline