Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl's correspondent string literal for Python's prefix r"text"?

This thread is about Python's string literal r, while this is about Perl's one here. However, I am not sure if there exists any equivalent command in Perl for Python's prefix r.

How can you replace equivalently Python's prefix r in Perl's string literals?

like image 277
Léo Léopold Hertz 준영 Avatar asked Jul 02 '15 12:07

Léo Léopold Hertz 준영


1 Answers

The uninterpolated quote operator q{} will get you most of the way there. There are only a couple of subtle differences.

  1. delimiters

    There are four delimiters used with Python raw string literals:

    • r"..." and r'...'
    • r"""...""" and r'''...'''

    The q... operator in Perl has a greater variety of delimiters

    • Paired delimiters q(...), q[...], q<...>, q{...}
    • Regular delimiters can be any other non-alphanumeric, 7-bit ASCII char: q"...", q/.../, q#...#, etc.
  2. the backslash

    The backslash character \ is always interpreted as a literal backslash character in Python raw literal strings. It will also escape a character that would otherwise be interpreted as the closing delimiter of the string

    r'Can\'t believe it\'s not butter'   =>   Can\'t believe it\'s not butter
    

    The backslash character \ in a Perl q{...} expression is also a literal backslash with two exceptions:

    • The backslash precedes a delimiter character

      q<18 \> 17 \< 19>     =>   18 > 17 < 19
      q#We're \#1#          =>   We're #1
      
    • The backslash precedes another backslash character. In this case the sequence of two backslash characters is interpreted as a single backslash.

      q[single \ backslash]           =>  single \ backslash
      q[also a single \\ backslash]   =>  single \ backslash
      q[double \\\ backslash]         =>  double \\ backslash
      q[double \\\\ backslash]        =>  double \\ backslash
      

There is one way to create a truly "raw" string in Perl: A single-quoted here-doc.

my $string = <<'EOS';
'"\\foo
EOS 

This creates the string '"\\fooNEWLINE.

(So is it possible to create a single raw string literal in Python that contains both ''' and """?)

like image 113
mob Avatar answered Sep 18 '22 09:09

mob