In this part of Perl cgi code $_ variable failed to print its contents inside <td> tag using Perl cgi?
sub do_work {
my $fh = shift;
my $content;
while ( my $line= <$fh> ) {
my @name1 = grep {$_ =~ m/^\[/} $line;
s/\W//g for @name1;
$content .= join '', @name1;
}
return $content;
}
sub do_task {
my $fh = shift;
my $load;
while(my $firstline = <$fh>) {
$firstline =~ s/.*=//g;
my @words = split /,., $firstline;
my $add = 0;
$load1 .= join("\n", @words);
}
return $load1;
}
sub layout {
my ($load, @words = @_;
my $add = 0;
print << "EOF";
<html><body><table>
<tr>
<th>s.no</th>
<th>name</th>
</tr>
EOF
foreach(@words) {
$add++;
print<<"EOF"
<tr>
<td>$add</td>
<td>$_</td>
EOF
}
print <<"EOF"
</table></body></html>
EOF
}
Description :
- To read the @words again and again i had used foreach loop. Here
@wordsare read from the previous subroutine. I tried to load the same array contents into the<td>tag. But from my code it is not getting the into the foreach? Because of what mistake it is not loading its contents.
Expected output:
From $load1 it got the following output:
hardware
software
os
So i tried to print it in table i.e inside <td> tag so i had used the foreach loop to take default value.
Now i expect my output should be as follows:
s.no name
1 Hardware
2 Software
3 os
1 Answer 1
The EOF marker for the HEREDOC needs to be all the way on the left. It cannot have leading whitespace. Because of that, there should be a syntax error because the rest of your code is not recognized as code by the parser.
It should look like that.
sub layout
{
my($load)=@_;
my @words=@_;
my $add=0;
print << "EOF";
<html><body><table>
<tr>
<th>s.no</th>
</tr>
EOF
foreach(@words)
{
$add++;
print<<"EOF"
<tr>
<td>$add</td>
<td>$_</td>
EOF
}
print <<"EOF"
</table></body></html>
EOF
}
Indented HEREDOCs will probably be available with Perl 5.26. A new feature was released with the development version 5.25.7 that introduces new syntax <<~"EOF". But you likely do not have that version, or a newer one.
In addition to that, you are putting the first argument of the function in $load, but also into @words. That's probably wrong. That should be my ($load, @words) = @_.
my @words = split /,., $firstline;andmy ($load, @words = @_;. If you can't take the time to make your code even compile, then why should we spend time looking at it?