in reply to Substituting literal strings for escape characters


Here is one way:
#!/usr/bin/perl -wl use strict; my %esc = ( '\0' => "\0", '\a' => "\a", '\b' => "\b", '\t' => "\t", '\n' => "\n", '\v' => "\013", '\f' => "\f", '\r' => "\r", ); my $literal = 'aaa\tbbb\nccc\tddd\t\\\\end'; (my $escaped = $literal) =~ s/(\\.)/exists $esc{$1} ? $esc{$1} : $ +1/eg; print $literal, "\n"; print $escaped; __END__ Prints: aaa\tbbb\nccc\tddd\t\\end aaa bbb ccc ddd \\end

Backslash has to be escaped in single quoted strings so it doesn't require a substitution.

The escape characters shown are the usual shell escapes. Perl adds a few more such as \e. Note the exists() isn't strictly required.

--
John.

Replies are listed 'Best First'.
Re: Re: Substituting literal strings for escape characters
by xmath (Hermit) on Feb 18, 2003 at 16:15 UTC
    This is a lot more complex than it needs to be, and only recognizes a small subset of possible scapes. Plus, there are escapes with an argument (like \012 or \x0A or \cJ for newline), which would make a very big hash or more complex code.

    A regex-with-eval-substitution like the ones below is a better solution.