Search code examples
perlstring-literals

Perl q function or single quote doesn't return the string literal of UNC path correctly


Perl's q function or single quote is supposed to return the string literal as typed (except \'). But it doesn't work as expected for the following scenario. I want to print the following UNC path

\\dir1\dir2\dir3

So I have used

my $path = q(\\dir1\dir2\dir3); 

OR

my $path = '\\dir1\dir2\dir3'; 

But this skips one backslash at the front. So if I print it i.e. print $path; it prints

\dir1\dir2\dir3

I want to know why? I have to type 3 or 4 backslashes at the beginning of the UNC path to make it work as expected. What am I missing?


Solution

  • From perldoc perlop:

    q/STRING/

    'STRING'

    A single-quoted, literal string. A backslash represents a backslash unless followed by the delimiter or another backslash, in which case the delimiter or backslash is interpolated.

    Change:

    my $path = q(\\dir1\dir2\dir3);
    

    to:

    my $path = q(\\\dir1\dir2\dir3);
    

    As for why, it's because Perl lets you include the quote delimiter in your string by escaping it with a backslash:

    my $single_quote = 'This is a single quote: \'';
    

    But if a backslash before the delimiter always escaped the delimiter, there would be no way to end a string with a backslash:

    my $backslash = 'This is a backslash: \'; # nope
    

    Allowing backslashes to be escaped too takes care of that:

    my $backslash = 'This is a backslash: \\';