Search code examples
perlcgi

Failed to pass variable from one sub routine to another sub routine using perl cgi?



Here i had tried to pass variable from one sub routine to another sub routine using perl cgi.But my variable is not passing from one sub routine to another,

use strict;
use warnings;
use CGI ':standard';
print header;
print start_html("example");
print end_html;
my $file = "text.txt";
open my $fh,'<', $file or die $!;
sub1($fh);
sub2($fh);

sub sub1 {
   my $fh = shift;
   while ( my $line = <$fh> ) {
      print $line;
   }
   return $fh;
}

sub sub2 {
   my $line = shift;
   print start_form;
   print "<table>";
   print "<th>content</th>";
   print "<tr>";
   print "<td>$line<td>";
   print "</tr>";
   print "</table>";
   print end_form;
}

In the above sub routine (i.e sub2 $line contents are not passing from sub1)


Solution

  • Maybe you wanted

    my $content = sub1($fh);
    sub2($content);
    
    sub sub1 {
        my $fh = shift;
        my $content;
        while ( my $line = <$fh> ) {
            print $line;
            $content .= $line;
        }
        return $content;
    }
    

    Also file handle $fh can be close after sub1 call