Splatt has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to write a script to compile some java code, but I think I'm not writing the slashes correctly. I'm trying to do it like this: $java_opt = "-g"; $class_dir = $ENV{CLASS_DIR}; $MakeMain = "javac $java_opt $class_dir\comm\client\Main.java"; system($MakeMain); The compilation bombs out. I think that it's interpreting the slash characters wrong. Do I need to put another slash in front of them, or what?

Replies are listed 'Best First'.
Re: Use of slashes and backslashes?
by Fastolfe (Vicar) on Oct 06, 2000 at 22:19 UTC
    In double-quoted strings, back-slashes are interpolated. The sequence \cX will be interpolated as a control-X. You can rewrite this in two forms:
    $MakeMain = 'javac ' . $java_opt . ' ' . $class_dir . '\comm\client\Main.java'; $MakeMain = "javac $java_opt $class_dir\\comm\\client\\Main.java";
    See perlop for information about single- and double-quoted strings.

    Update: This can actually all be done a little cleaner:

    @MakeMain = ('javac', $java_opt, $class_dir.'\comm\clients\Main.java'); system(@MakeMain);
    This has the added benefit of keeping your code a little more secure against tampering, by using unsafe data in $java_opt or $class_dir (or potentially so, since I have no idea how you're getting this data). Plus using system() in this form is faster, since it doesn't have to spawn off a shell interpreter to parse your string. If $java_opt as a set of options separated by spaces, though, it won't work very well. You'd either need to split the string or just go with the full string version as you are doing in your original code.