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

I need to take a string and every instance of ' I need to add a \ so that it works in a system command. thanks

Replies are listed 'Best First'.
Re: finding '
by Zaxo (Archbishop) on Jun 15, 2002 at 01:46 UTC

    In system calls, it's helpful to use the list form of argument. That calls the system program directly, without giving the shell a chance to reinterpret your other arguments:

    system '/bin/touch', q(/unhelpfully/named/AM's File);

    After Compline,
    Zaxo

Re: finding '
by Baboon (Acolyte) on Jun 15, 2002 at 00:46 UTC
    quotemeta is one but not only way to do this...

    Best wishes,
    I.R.Baboon.

      Actually quotemeta will quote all non alphanumeric characters which is rather more than the original querient was after :)

      I would suggest some variant of:     s#\'#\\\'#g;

      --
      my $chainsaw = 'Perl';

Re: finding '
by mfriedman (Monk) on Jun 15, 2002 at 05:21 UTC
    I prefer

    $string =~ s/([^\])\'/$1\\\'/g;

      For a different variation on the same theme, try

      $string =~ s/(?<!\\)'/\\'/g;

      Though this raises the question "what if the string contains a backslash followed by a single quote?" Which makes the regex slightly more complicated, and leads back to he conclusion that quotemeta might not be such a bad idea, after all...

      Update: while I'm writing silly regexes...

      $string =~ s/(?<!\\)(?=')/\\/g;

      <duck>



      If God had meant us to fly, he would *never* have given us the railroads.
          --Michael Flanders

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: finding '
by Anonymous Monk on Jun 15, 2002 at 01:11 UTC
    It's ok, I battled through and got it to work! Horray for me! :-)
A reply falls below the community's threshold of quality. You may see it by logging in.