in reply to Formatting quotes in a String

Are you asking how to add a closing double quote to a string?
$string .= '"'; # or substr $string, length $string, 0, '"'; # or $string =~ s/$/"/;

If you only want to add it when needed, just count the double quotes first, and only add it when the number is odd:

$string .= '"' if ($string =~ tr/"//) % 2;

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^2: Formatting quotes in a String
by pavan474 (Novice) on Dec 01, 2016 at 07:26 UTC

    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

      .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

      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