in reply to Re: CGI: Passing variables to a subroutine
in thread CGI: Passing variables to a subroutine

Thanks for the response

If I have to pass other variables that are not a part of the $query object, I presume that I should be passing that to the subroutine.

Please look at the modified code below:- Any suggestions?

use CGI; my $query = CGI->new(); # get the data structure my $ref_data= create_data_structure(); if ($query->param( "button" ) eq 'first') { display_first( $query, $ref_data ) } else { display_second( $query, $ref_data ) } sub display_first { my ( $query, $s1_data ) = @_; # declare your variables here ... # use $s1_data to do something in this sub } sub display_second { my ( $query, $s2_data ) = @_; # declare your variables here ... # use $s2_data to do something in this sub } sub create_data { ... create a hash data structure ... ... return \%hash; }

Replies are listed 'Best First'.
Re^3: CGI: Passing variables to a subroutine
by ikegami (Patriarch) on Jan 04, 2007 at 22:17 UTC

    Use a dispatch handler.

    my %handlers = ( first => \&display_first, second => \&display_second, ... ); my $handler = $handlers{$query->param( "button" )}; if (!$handler) { ... } $handler->($query, $region, $var1, $var2, $var3);

    You might even want to make some of those variables global, especially if they aren't changed after being set. Alternatively, the handler could use $query to get the variables it needs.

Re^3: CGI: Passing variables to a subroutine
by friedo (Prior) on Jan 04, 2007 at 23:09 UTC

    You don't actually need to pass $ref_data as an argument to your subroutines, because they're already in its lexical scope. (They can "see" it already.)

    But, it's good practice to keep the scope of things as small as possible, so why not just call create_data() in each of the subroutines where you need it? (Presumably, only one of them will be running per CGI request anyway.)

    And I second the suggestion of using a dispatch table. There's also CGI::Application, which is like a dispatch table on steroids with all sorts of nifty OO stuff and plugins.