in reply to passing string to stdin on exec-command

Abigail-II has provided a good solution. However on a unix system, I would probably 'cheat' a bit -
my $str = 'blah blah'; system("echo '$str' | cmd -option");
I suspect this might even work under DOS too. :)

Update: As 3dan has pointed out, this solution is flawed and doesn't work properly. However I could try to insert back slashes in front of single quotes in the input string, but that's just creating more unnecessary work and not worth the efford.

However I will not reap this node, I will leave it here as a typical negative example of how not to do it.

Replies are listed 'Best First'.
Re: Re: passing string to stdin on exec-command
by edan (Curate) on Nov 05, 2003 at 14:13 UTC
    my $str = q(Aren't you glad you listened to Abigail and not Roger?); system("echo '$str' | cat"); __output__ sh: -c: line 1: unexpected EOF while looking for matching `'' sh: -c: line 2: syntax error: unexpected end of file
    --
    3dan

      And that brings us to the question, how do you escape single quotes in the shell? The answer is not putting a backslash in front of a single quote. In the shell, a backslash does not have a special meaning when it's inside single quotes. But then what?

      The answer lies in the fact that the shell does concatenation by absense of whitespace. So, if we want to put O'Reilly inside quotes, we break the string into three parts: O, ' and Reilly. The first and last part will be surrounded by single quotes, the single quote will be surrounded by double quotes, and then we stick the three parts together, resulting in: 'O'"'"'Reilly'. This sounds complicated, but we can do this with a single substitution: s/'/'"'"'/g.

      #!/usr/bin/perl use strict; use warnings; while (<DATA>) { chomp; my $orig = $_; s/'/'"'"'/g; my $result = `echo '$_' | cat`; chomp $result; print STDERR "Mismatch [$orig] vs [$result]\n" unless $result eq $ +orig; } __DATA__ foo bar 'foo bar' foo'"'bar '''''''''''' ''''''''''' "foo'bar" "foo''bar" "foo'bar"" ' "'"

      Abigail

        And this is why you should be thankful that system() and qx() use only /bin/sh and never "the user's preferred shell", because /bin/csh cannot quote all possible strings. I can't recall the combo you can't get now, but I think it's a backslash followed by a newline that cannot be quoted, because one backslash and a newline just creates a newline, but two backslashes and a newline creates two backslashes and a newline, or something like that.

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.

      Thanks 3dan, very good point ++. Yes you are right. I have forgotten about single quotes in input strings.