سؤال

I have to read values from a file, store them in an array and then output the values into an HTML table in an HTML file. What is the best way to do this? Using write() and format to write to the file, using CGI and print to write to the file, or just printing tr's and td's?

I have three columns and four rows (12 values).

هل كانت مفيدة؟

المحلول 2

Just use format and write(), and a loop to control the input. Like this:

    while($i<10){
        $name = $values[$i];
        $description = $values[$i+1];
        $price = $values[$i+2];
        write;
        $i = $i+3;
    }


    format BODY =
    <tr><td>@*</td><td>@*</td><td>$@####.##</td></tr>
            $name,          $description,                         $price
    .

نصائح أخرى

I love formats, but I wouldn't use it for this. The things formats do and are good at don't come into play here.

Simple print statements will do. splice is an under-appreciated built-in that can remove several elements from an array in one go:

use HTML::Entities qw(encode_entities);

my @values = (
    'a' .. 'd',
    'cats & dogs', '</div>', '"quotes"',
    '<script src="foo.js"/>',
    'e' .. 'f'
    );

my $elements_per_row = 3;

print "<table>\n";
while( my @row = splice @values, 0, $elements_per_row, () ) {
    print 
        '<tr>',
        map( 
            { '<td>' . encode_entities( $row[$_] ) . '</td>' } 
            0 .. $elements_per_row - 1
            ),
        '</tr>', "\n"
    }
print "</table>\n";

But, you should think about separating your HTML from your program using a templating system of some sort. There are several available for Perl.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top