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

In this code i am having a hard time matching "a+b" as an argument. If i insert "a\\+b" as an argument it works. I am wondering if there is another way around this so that it works with "a+b" as an argument.
use strict; my $var1 = $ARGV[0]; print $var1."\n"; open(IN, "temp.mine") or die "Error opening temp.mine\n"; while(<IN>) { my $line = $_; print "input = $line\n"; if($line =~ /$var1/m) { print "found \n"; close(IN) or die "Error closing file\n"; exit 0; } } close(IN) or die "Error closing temp.mine\n"; print "not found \n"; #contents of file temp.mine #a+b
i am working on a larger program where i am having an error due to the above problem. Please if anyone knows a way i can match this without changing my input argument or the temp.mine file let me know asap. Thanks Waris

Replies are listed 'Best First'.
Re: matching + character in a file
by tachyon (Chancellor) on Aug 07, 2001 at 01:05 UTC

    Please have a look at all the answers you got at matching the + character. In short do either of these:

    $var1 = quotemeta $var1; # do this before you use it in the regex or if ($line =~ /\Q$var1\E/m)

    Either of these escape all regex metachars and should be considered mandatory if you want to avoid problems interpolating variables into regexes. PS Don't do both at the same time - it is either or!

    cheers

    tachyon

    print quotemeta 'a+b';

Re: matching + character in a file
by runrig (Abbot) on Aug 07, 2001 at 01:08 UTC
2 small things
by dga (Hermit) on Aug 07, 2001 at 02:54 UTC
    1. print $var1."\n"; ... 2. if($line =~ /$var1/m) ...

    1. You might want to

    print "$var1\n"; #similar look and obvious function OR print $var1, "\n"; #efficiency

    The first looks like your other print usages and does the most obvious thing (prints the variable and a newline)

    The second is a bit more efficient because there is no concatenation of 2 strings followed by a print of the result. print is a list operator which pops out its arguments one after the other, in this case $var1 followed with no space by "\n"

    2. In the code sample (with that while) you should only get one line so I dont see a need for the /m modifier do do multiline matching.

Re: matching + character in a file
by mischief (Hermit) on Aug 07, 2001 at 15:00 UTC

    If all you're doing is trying to match a '+', another way to do this would be with the index function:

    #!/usr/bin/perl -w use strict; my $a = '123a+b456'; print "found\n" unless index($a, 'a+b') == -1;

    I'm not entirely sure how efficient that is, though (but I have a suspicion it's more efficient than attempting a full regex match).