I'm having trouble understanding command argument quotations for perl in Windows. Using the following program:
use strict;
use warnings;
use File::Find;
use File::Copy;
my $dir = shift;
die 'Usage: perl Folderize.pl <directory>' unless $dir;
die "$dir doesn't exist" unless -d $dir;
I get different results depending on if I use single or double quotes for a directory. If I call it with 'perl script.pl 'H:\Test!'
it prints "'H:\Test!' doesn't exist". However, if I call it with 'perl script.pl "H:\Test!"
, it works just fine. Why is this happening?
There is no such difference between the single quote (') and double quote(“) in PowerShell. It is similar to a programming language like Python.
The main difference between double quotes and single quotes is that by using double quotes, you can include variables directly within the string.
If you put a back-slash \ in a double-quoted string, Perl will think you want to escape the next character and do its magic.
Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc. Enclosing characters in single quotes ( ' ) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
On the command-line, quoting rules are the purview of the shell, not the program (perl). The rules for Unix shells are similar to the rules for Perl (double quote interpolates variables, single quotes don't) but the Windows "shell" has different rules. Some main differences are:
Single quote '
is not a special character
C:>\ dir > 'foo'
will create a file called 'foo'
(the quotes will be included in the filename)
""
double quotes interpolate environment variables that look like %NAME%
, but it won't try to interpret perl scalar variable names as environment variables:
C:>\ perl -e "print '%PATH'"
The Windows shell will "close" your quote for you if you forget
C:>\ perl -e "print qq/Hello world/
Hello world
This works even though I forgot to use the second double quote.
This has nothing to do with the Perl interpreter. It is the shell that interprets commands and their arguments.
When you supply a double-quoted argument, for example "H:\Test!"
, the shell treats everything inside the quotes as the contents of the string, and what is passed to the Perl interpreter is the string without the quotes.
By contrast, when you supply 'H:\Test!'
, the shell takes the single quotes as a part of the string itself, and passes it this way to the Perl interpreter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With