Вопрос

I need to be able to send a file stream and a byte array as a response to an HTTP POST for the testing of a product. I am using CGI perl for the back end, but I am not very familiar with Perl yet, and I am not a developer, I am a Linux Admin. Sending a string based on query strings was very easy, but I am stuck on these two requirements. Below is the script that will return a page with Correct or Incorrect depending on the query string. How can I add logic to return a filestream and byte array as well?

#!/usr/bin/perl
use CGI ':standard';

print header();
print start_html();

my $query = new CGI;
my $value = $ENV{'QUERY_STRING'};


my $number = '12345';

if ( $value == $number ) {
print  "<h1>Correct Value</h1>\n";
} else {
print "<h1>Incorrect value, you said: $value</h1>\n";
}
print end_html();
Это было полезно?

Решение

Glad to see new people dabbling in Perl from the sysadmin field. This is precisely how I started.

First off, if you're going to use the CGI.pm module I would suggest you use it to your advantage throughout the script. Where you've previously inputted <h1> you can use your CGI object to do this for you. In the end, you'll end up with much cleaner, more manageable code:

#!/usr/bin/perl
use CGI ':standard';

print header();
print start_html();

my $value = $ENV{'QUERY_STRING'};
my $number = '12345';

if ( $value == $number ) {
    h1("Correct Value");
} else {
    h1("Incorrect value, you said: $value");
}

print end_html();

Note that your comparison operator (==) will only work if this is a number. To make it work with strings as well, use the eq operator.

A little clarification regarding what you mean regarding filestreams and byte arrays ... by file stream, do you mean that you want to print out a file to the client? If so, this would be as easy as:

open(F,"/location/of/file");
while (<F>) {
    print $_;
}
close(F);

This opens a file handle linked to the specified file, read-only, prints the content line by line, then closes it. Keep in mind that this will print out the file as-is, and will not look pretty in an HTML page. If you change the Content-type header to "text/plain" this would probably be more within the lines of what you're looking for. To do this, modify the call which prints the HTTP headers to:

 print header(-type => 'text/plain');

If you go this route, you'll want to remove your start_html() and end_html() calls as well.

As for the byte array, I guess I'll need a little bit more information about what is being printed, and how you want it formatted.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top