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

New to GD:Graph. I have tried several examples from site to test module. All result in some unicode string. What is my problem? Thanks

#!/usr/bin/perl -w use 5.010; use strict; use warnings; use GD::Graph::bars; print"Hello world!\n"; my @data =([1,2,3,4],[5,3,8,9]); my $graph = GD::Graph::bars->new(400,300); $graph->set( x_label => 'X num', y_label => 'Y num', title => 'Test', ) or warn $graph->error; my $myimage = $graph->plot(\@data) or die $graph->error; print "Content-type: image/png\n\n"; print $myimage->png;

Replies are listed 'Best First'.
Re: gd::graph returns unicode
by kennethk (Abbot) on Jul 09, 2013 at 16:51 UTC
    Since you are printing binary image data, you should be setting binmode:
    binmode STDOUT; print $myimage->png;
    Also, if you are writing a web service, I'd suggest using CGI rather than rolling your own headers. See Ovid's CGI Course - Resurrected and Updated! for a tutorial.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      Thanks. works.

Re: gd::graph returns unicode
by Khen1950fx (Canon) on Jul 09, 2013 at 19:43 UTC
    According to the author, the use of @data is legacy code. I rewrote it to reflect the newer usage. Note that the usual way to print is...
    open(IMG, '>test.png'); binmode IMG; print IMG $gd->png;
    The full script:
    #!/usr/bin/perl -l use strict; use warnings; use GD::Graph::bars; use GD::Graph::Data; print "Hello world!\n"; my $data = GD::Graph::Data->new([ [1,2,3,4], [5,3,8,9], ]) or die $!; my $graph = GD::Graph::bars->new(); $graph->set( x_label => 'X num', y_label => 'Y num', title => 'Test', ) or die $graph->error; my $gd = $graph->plot($data) or die $!; open(IMG, '>test.png'); binmode IMG; print IMG $gd->png;