open my $fh => "| cmd -option" or die $!;
print $fh $str;
close $fh or die $!;
Abigail | [reply] [d/l] |
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.
| [reply] [d/l] |
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
| [reply] [d/l] |
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 | [reply] [d/l] [select] |
Thanks 3dan, very good point ++. Yes you are right. I have forgotten about single quotes in input strings.
| [reply] |