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

Hello Monks,

I have strings in an array "@col" in all elements of this array there is one operator like "." or "+". Which is already stored in "$operator".

What i want is string on left & right side of the operator in each element of the array.

My code is like
foreach(@col){ my $celldata=$_; $celldata=~s/<(set|x)?aln;(.*?)>//g; $celldata=~s/<(rct|rrt|rlt)?;(.*?)>//g; $celldata=~s/(<T(?:r|c)>)//g; #print "$celldata\n"; if($celldata=~m{(.+?)$operator(.*)}){ $left_str=$1; $right_str=$2; print "$left_str === $operator + === $right_str\n"; } }
Suppose @col contains elements like "2.2", "3.2", "1.3", "11.5" etc.. when i print left and right string for "11.5" it gives output as "1===.===.5". However I want "11===.===5"". I dont know what is wrong with the perticular pattern.

Can anybody please help me?

Thank you.

Replies are listed 'Best First'.
Re: Something is wrong with this pattern
by samarzone (Pilgrim) on Dec 24, 2010 at 06:55 UTC

    The value inside $operator (supposed to "." in case of "11.5") is interpreted as special character inside regular expression. Escape its special meaning as following

    $celldata=~m{(.+?)\Q$operator\E(.*)}

    You can better use split for this if you have only one "$operator" in a string

    ($left_str, $right_str) = split(/\Q$operator\E/, $celldata);

    -- Regards - Samar

      Thank you samarzone

      It is working fine now...
Re: Something is wrong with this pattern
by GrandFather (Saint) on Dec 24, 2010 at 06:34 UTC

    What does $operator contain?

    As a general comment: .+? at the start or end of a regex will never match anything - don't do that. It's also good practise to use a character set in place of . when using * to avoid capturing more than you intend.

    True laziness is hard work
      As a general comment: .+? at the start or end of a regex will never match anything
      False:
      $ perl -wE '"abcdef" =~ /(.+?)f/ and say $1' abcde
      Remember, "left-most match" trumps "shortest match".

        Sigh, yes you are quite right and I didn't remember. Can we blame it on too much pre-Christmas cheer? Merry Christmas. ;)

        True laziness is hard work