How can I prevent Perl from interpreting double-backslash as single-backslash character?

后端 未结 3 1845
深忆病人
深忆病人 2021-01-14 09:32

How can I print a string (single-quoted) containing double-backslash \\\\ characters as is without making Perl somehow interpolating it to single-slash \\

3条回答
  •  悲哀的现实
    2021-01-14 09:59

    Since the backslash interpolation happens in string literals, perhaps you could declare your literals using some other arbitrary symbol, then substitute them for something else later.

    my $string = 'a!!!b';
    $string =~ s{!}{\\}g;
    print $string; #prints 'a\\\b'
    

    Of course it doesn't have to be !, any symbol that does not conflict with a normal character in the string will do. You said you need to make a number of strings, so you could put the substitution in a function

    sub bs {
        $_[0] =~ s{!}{\\}gr
    }
    
    my $string = 'a!!!b';
    print bs($string); #prints 'a\\\b'
    

    P.S. That function uses the non-destructive substitution modifier /r introduced in v5.14. If you are using an older version, then the function would need to be written like this

    sub bs {
        $_[0] =~ s{!}{\\}g;
        return $_[0];
    }
    

    Or if you like something more readable

    sub bs {
        my $str = shift;
        $str =~ s{!}{\\}g;
        return $str;
    }
    

提交回复
热议问题