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

since my chef wants to use a script i have written on a win2000 machine i have to work a bit on it. there rests this one little problem: how to escape characters like spaces to pass as argument to another script:

i have written a little code to make the problem more obvious:

  • tell.pl
    use strict; use warnings; my $string1 = " koisqd / \ poqsdpo .posd"; my $string2 = " koisqd / \ poqsdpo .posd"; my $string3 = " koisqd / \ poqsdpo .posd"; foreach my $toEscape ($string1, $string2, $string3){ $toEscape =~ s/(\s|\\|\/)/\\$1/g; } system("perl hear.pl $string1 $string2 $string3");
  • hear.pl
    use strict; use warnings; my $i = 1; foreach my $arg (@ARGV){ print "$i\t: $arg\n"; $i++; }
    wich gives me:
    1 : \ 2 : koisqd\ 3 : \/\ 4 : \ 5 : poqsdpo\ 6 : .posd 7 : \ 8 : koisqd\ 9 : \/\ 10 : \ 11 : poqsdpo\ 12 : .posd 13 : \ 14 : koisqd\ 15 : \/\ 16 : \ 17 : poqsdpo\ 18 : .posd
    instead of just 3 arguments...

    please help me

    ----
    NaSe
    :x

  • Replies are listed 'Best First'.
    Re: Escaping characters on win2000's cmd.exe
    by PodMaster (Abbot) on Aug 22, 2002 at 12:20 UTC
      1. you bust out your shell's manual, and learn that it ain't *nix (you can't escape spaces, you need to "quote" stuff).

      2. this is also documented in perlrun, don't you ever perl -e " die scalar gmtime " ?

      my $arg = q{butteer "scotch"}; $arg =~ s{"}{\\"}g; system (qq{blah "$arg" ....});
      update: also, perldoc -f system

      ____________________________________________________
      ** The Third rule of perl club is a statement of fact: pod is sexy.

        thanks that helped and it works now

        ----
        NaSe
        :x

    Re: Escaping characters on win2000's cmd.exe
    by JupiterCrash (Monk) on Aug 22, 2002 at 13:08 UTC
      In addition to just quoting the arguments, which is a good start, you should note that perl's system command can accept an array as its argument. Like this:

      @args = ("command", "arg1", "arg2");
      system(@args);

      This is a nice solution, because then you don't have to worry about escaping things (like quotes) that the OS does not like in the arguments themselves.