I want to wrap a perl one-liner in a batch file. For (trivial) example, in a unix shell I could quote up a command like this:

perl -e 'print localtime() . "\n"'

But DOS chokes on that with the helpful

Can't find string terminator "'" anywhere before EOF at -e line 1.

What's the best way to do this within a .bat?

+10  A: 

For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning toothpick syndrome. I save the quotes for the stuff that DOS needs:

perl -e "print scalar localtime() . qq(\n)"

If you just need a newline at the end of the print, you can let the -l switch do that for you:

perl -le "print scalar localtime()"

For other cool things you can do with switches, see the perlrun documentation.

brian d foy
The great thing about this is that it also works on Linux.
Brad Gilbert
+7  A: 

In Windows' "DOS prompt" (cmd.exe) you need to use double quotes not single quotes. For inside the quoted Perl code, Perl gives you a lot of options. Three are:

perl -e "print localtime() . qq(\n)"
perl -e "print localtime() . $/"
perl -le "print ''.localtime()"

If you have Perl 5.10 or newer:

perl -E "say scalar localtime()"

Thanks to J.F. Sebastian's comment.

good answer, just marginally less good than the one I accepted. Thanks!
Jeff Youngstrom
perl -le "print localtime()" -- prints '2625625810842681' instead of 'Thu Sep 25 06:25:26 2008', perl -E"say scalar localtime
J.F. Sebastian
This also works [may print "Tue Aug 4 02:54:07 2009"]: perl -le "print scalar localtime()"
Peter Mortensen
+1  A: 

In DOS, you use the "" around your perl command. The DOS shell doesn't do single quotes like the normal unix shell.

perl -e "print localtime();"
David Nehme
+1  A: 

First, any answer you get to this is command-specific, because the DOS shell doesn't parse the command-line like a uniq one does; it passes the entire unparsed string to the command, which does any splitting. That said, if using /subsystem:console the C runtime provides splitting before calling main(), and most commands use this.

If an application is using this splitting, the way you type a literal double-quote is by doubling it. So you'd do

perl -e "print localtime() . ""\n"""
+1  A: 

For general batch files under Windows NT+, the ^ character escapes lots of things (<>|&), but for quotes, doubling them works wonders:

C:\>perl -e "print localtime() . ""\n"""
Thu Oct  2 09:17:32 2008