Search code examples
perlgnuplotpipingvariable-expansion

Use variable expansion in heredoc while piping data to gnuplot


I normally use a code like following to pipe data from a file to gnuplot and create a picture during the Perl script:

#!/usr/bin/perl
use warnings;
use strict;

my $in="file.dat";

open(GP, "| gnuplot") or die "$!\n";
print GP << "GNU_EOF";

set terminal png size 1920,1080 font 'Verdana,15' dashed
set output 'out.png'
plot "$in"

GNU_EOF

close(GP);

I have to define "GNU_EOF" instead of 'GNU_EOF' so I can use variables like $in.

Now I want to use data which isn't read from a file directly. My code looks like:

#!/usr/bin/perl
use warnings;
use strict;

open(GP, "| gnuplot") or die "$!\n";
print GP << 'GNU_EOF';

set terminal png size 1920,1080 font 'Verdana,15' dashed
set output 'out.png'
plot '-'

GNU_EOF

open(INFILE,"< stuff.dat") or die "$!\n";
while (my $line = <INFILE>) {

for my $i (1..10){
    # do some stuff to calculate my data points stored in $x and $y
    print GP "$x $y\n";
}
print GP "EOF\n";
}

close(INFILE);
close(GP);

If I try this using "GNU_EOF" to be able to define variables in the heredoc, I am getting errors like:

gnuplot> 187 0.05
         ^
         line 1: invalid command

I don't know

  • why I have to use "" for the heredoc to get the desired variable expansion and

  • why I get errors for the second example.

Help is highly appreciated.


Solution

  • I solved it. Sorry for the incomplete question, I wanted to give a minimal example to avoid confusion. Unfortunately my question missed the important part. Like said in the comments I use several loops to generate data and pipe it to gnuplot:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    open(GP, "| gnuplot") or die "$!\n";
    print GP << 'GNU_EOF';
    
    set terminal png size 1920,1080 font 'Verdana,15' dashed
    set output 'out.png'
    plot    '-' t "one", \
            '-' t "two"
    
    GNU_EOF
    
    open(INFILE,"< stuff.dat") or die "$!\n";
    while (my $line = <INFILE>) {
    
    for my $i (1..10){
        # do some stuff to calculate data points stored in $x and $y
        print GP "$x $y\n";
    }
    print GP "EOF\n";
    }
    
    for my $i (1..50){
        # do some other stuff to calculate data points stored in $x and $y
        print GP "$x $y\n";
    }
    print GP "EOF\n";
    }
    
    close(INFILE);
    close(GP);
    

    I don't know why, but using 'GNU_EOF' (without variable expansion) I can define several plot with the line brake command \.

    Using "GNU_EOF" I have to define it in one line:

    plot '-' t "one", '-' t "two"
    

    Sorry for the struggle, but maybe this is also helpful for someone else (and maybe you can explain this behaviour to me).