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

Dear Perl Monks,

I have a situation with regex and a function call which dumps some junk (control) characters in match variables($1, $2)
The codes are something like below,

If($str =~ m/(pattern1)(pattern2)/gi) { $str = &function($1); $var1 = &function($2); }
Here $var1 is getting some junk control characters which was never part of match. Could you please help to get some light into why this is happening?
When we try to put these codes in a different way, i.e. not making use of $2 – everything works fine – i.e. without any junk characters. Something like below,
If($str =~ m/(pattern2)/gi) { $var1 = &function($1); If($str =~ m/(pattern1)pattern2/gi){ $str = &function($1); } }
On another note, code-1: works fine on Windows system and shows junk Only on Linux. Code-2, works fine on both systems.

Many Thanks,

Replies are listed 'Best First'.
Re: Regex, Function and Default variables
by kcott (Archbishop) on Nov 20, 2013 at 07:48 UTC

    G'day tosaiju,

    $2 is probably being modified somewhere between the two calls to function().

    You've posted If instead of if. This should generate a syntax error. Instead of typing your code by hand when posting, copy and paste it: less effort; more accurate! It also means we're seeing your real code.

    Also, do you need the leading &s? See perlsub.

    Without seeing more of your code, I'd suggest something along these lines (untested):

    if ($str =~ m/(pattern1)(pattern2)/gi) { my ($arg1, $arg2) = ($1, $2); $str = function($arg1); $var1 = function($arg2); }

    -- Ken

Re: Regex, Function and Default variables
by GrandFather (Saint) on Nov 20, 2013 at 07:44 UTC

    Code that is "something like" doesn't often help. Much better to supply a small sample script that reproduces the problem. See I know what I mean. Why don't you?.

    True laziness is hard work
Re: Regex, Function and Default variables
by Anonymous Monk on Nov 20, 2013 at 07:48 UTC
Re: Regex, Function and Default variables
by oiskuu (Hermit) on Nov 20, 2013 at 11:57 UTC
    Also remember that m// behaves differently depending on context, flags, whether () groups are present...

    In particular, when $str =~ m//g is used in scalar context (as in your posted examples), it requests match position pos($str) to be remembered; further m//g continue from there. (But assigning to $str will forget the pos!)

    # m// in list context, no g flag if (my @match = $str =~ m/(pattern1)(pattern2)/i) { $str = function($match[0]); $var1 = function($match[1]); }

      First of all apologize for not giving the complete example or sample. Thanks a lot for the advice and solution; I think this is basically of function call – which overwrites the value. Thank you Monks