At 01:38 PM 1/16/2004, James Edward Gray II wrote:
>I have a problem I just cant seem to get my head around, so any help is appreciated.
>
>I have a string.  It could contain anything a Perl string can contain.  
>I have to print this string to a file and later bring it back in exactly as it was.  
>However, because of the file format, the string in the file may not contain \n 
>characters.  That's the only difference between the two representations of this 
>string.
>
>Okay, obviously I need to replace all \n characters.  Let's say I want to follow 
>Perl's example and use a literal \ followed by a literal n.  
>Then I would also need to escape \ characters.  Okay, again we'll use Perl's \ and 
>another \.  Does that cover everything if \n is the only illegal character in my file 
>format?  I believe, so, but please correct me if I'm wrong.
>
>The to file conversion seems simple given the above:
>
>$string =~ s/\\/\\\\/g;
>$string =~ s/\n/\\n/g;
>
>Does that work as good as I think it does?
>
>Now I have to get it back out of the file and that's where it falls apart on me.  
>I've tried things like:
>
>$string =~ s/((?:^|[^\\])(?:\\\\)*)\\n/$1\n/g;
>$string =~ s/\\\\/\\/g;
>
>While that gets close, it doesn't seem to work on everything.  Here's an example 
>(one-liner reformatted for easier reading):
>
>perl -e ' $test = "\tFunky \"String\"\\\n\n";
>        print "String:  $test\n";
>        $test =~ s/\\/\\\\/g;
>        $test =~ s/\n/\\n/g;
>        print "To File:  $test\n";
>        $test =~ s/((?:^|[^\\])(?:\\\\)*)\\n/$1\n/g;
>        $test =~ s/\\\\/\\/g;
>        print "From File:  $test\n" '
>String:         Funky "String"\
>
>
>To File:        Funky "String"\\\n\n
> From File:      Funky "String"\
>\n
>
>Any advice is appreciated.

I just had to do something like this yesterday, and I couldn't figure out how to do it 
in just one regex, but I did find a way that you could use.  I have a database giving 
me single and double quotes in variables as their octal equivalent.  I get a variable 
from the database as:

Dan\047s \042Baby\042

and I need the variable converted back to:

Dan's "Baby"

So, I did the following, @words is a list of variables to convert

        # change octal \0nn to the appropriate character
        foreach (@words) {
                while ($_ =~ /\\(0\d{2})/) {
                        my $myChar = chr(oct $1);
                        $_ =~ s/\\$1/$myChar/g;
                }
        }
This works, but I am sure there is a better way to code this, and I was thinking of 
asking that when I had time.  To use it, instead of coverting newlines to \n, convert 
them to \012.

-Mark



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to