in reply to Re: Formatting quotes in a String
in thread Formatting quotes in a String

Hi choroba,

The second one is what i am expecting only add when needed and this is working fine for my requirement.can you please get me through how this is working. I have checked on this logic So, tr usually returns the number of characters returned or removed. I tried checking this

$string = 'Tetsing " code implementationm'; $string = tr/"/ /; print $string;

output is coming as 0

Even i tried this

$string =~ tr/"//; print $string;

The output is the same input string

Thanks

Replies are listed 'Best First'.
Re^3: Formatting quotes in a String
by Laurent_R (Canon) on Dec 01, 2016 at 10:13 UTC
    .can you please get me through how this is working
    Your tests are not adequate to understand choroba's suggested code. Try this (demonstrated here under the Perl debugger):
    DB<1> $string = 'Tetsing " code implementationm'; DB<2> $result = $string =~ tr/"//; DB<3> p $result 1 DB<4> p $string Tetsing " code implementationm
    In essence, choroba is testing the value that ends up into $result in the code above. And it adds a quote mark at the end of the string if the value returned by tr/// is odd (meaning that quote marks are unbalanced).

      Thanks, Laurent_R

      I got how this is working

Re^3: Formatting quotes in a String
by perldigious (Priest) on Dec 01, 2016 at 14:18 UTC

    Hi pavan474,

    Regarding choroba's code with an attempt to supplement it with a text explanation:

    The ($string =~ tr/"//) portion provides a simple count of the number of double quotes contained within the string, it doesn't modify the string. He uses the modulo operator to divide this count by 2 and keep only the remainder, ($string =~ tr/"//) % 2. Due to the math, that remainder can only be 0 (if there were an even number of double quotes) or 1 (if there were an odd number of double quotes). Then he concatenates a double quote on to the end of the string, $string .= '"', but only if that remainder was 1 (an odd number of double quotes).

    UPDATE:

    Also consider the following if you wanted to check what the ($string =~ tr/"//) portion gives before and after the concatenation of the double quote on to your original string.

    $string = '"testing the data available'; print scalar ($string =~ tr/"//), "\n"; $string .= '"' if ($string =~ tr/"//) % 2; print ($string =~ tr/"//);

    Just another Perl hooker - will code for food