2
votes

I would like a Perl script to display a simple gnuplot graph. I don't want to store any data in a file, I want to use a gnuplot one-liner such as:

gnuplot -p <(echo -e 'plot "-"\n1 1\n2 3\n3 1.7\n4.5 5\ne')

That displays the points (1, 1), (2, 3), (3, 1.7) and (4.5, 5).

In a Perl script, I tried things like

$plotString  = "\"<(echo -e 'plot \\\"-\\\"\\n";
$plotString .= "1 1\\n2 3\\n3 1.7\\n4.5 5\\ne')\"";
system('gnuplot -p ' . $plotString);

but I get the following error:

-e plot "-"
^
"<(echo -e 'plot "-"\n1 1\n2 3\n3 1.7\n4.5 5\ne')", line 1: invalid command

This error surprises me because the string passed to system(), as quoted in the error message, is apparently correct.

Any idea how to modify $plotString so system() would correctly interpret the gnuplot command?

Secondary question: how to draw the graph with lines? (I couldn't get the gnuplot one-liner to do it, even outside Perl.)

Edit: My OS is Ubuntu 16.04.

1
Welcome to quoting hell. At a glance, it looks to me like you have an extra set of quotation marks around the variable. But you've wrapped things up in so many layers of quoting that it's difficult to tell. I suggest trying a simpler string and then gently building up to this. It's very possible that it's a simple escaping typo.Silvio Mayolo

1 Answers

5
votes
system($shell_cmd)

is short for

system('/bin/sh', '-c', $shell_cmd)

But what you have there is not a valid sh command, but a bash command. That means you'll need to invoke bash instead.

my $cmd = q{gnuplot -p <(echo -e 'plot "-"\\n1 1\\n2 3\\n3 1.7\\n4.5 5\\ne')};
system('bash', '-c', $cmd)

It appears you could also use the following to avoid creating two shells:

my $program = <<'__EOS__';
plot "-"
1 1
2 3
3 1.7
4.5 5
e
__EOS__

open(my $pipe, '|-', "gnuplot", "-p")
print($pipe $program);
close($pipe);