in reply to CGI::Application - alternative to using $self->param?

After you create the C::A instance, you can always stick it in a global variable:
my $cgi = new CGI::Applicaton(...); $::global_var = $cgi; ... use $::global_var now anywhere ...

A variable like $::global_var is a fully-qualified name which is as close as Perl gets to global variables. It is equivalent to $main::global_var or to using our in package main:

... { package main; our $global_var; # same as $::global_var and $main::global_var ... }

You can create a tie interface if you want to access parameters like you did with a hash. See man perltie for more details. However, if you are writing new CGI applications, I wouldn't do this. Just extract parameters into simple variables if you need to use them more than once. A tie interface would allow you to use hash-like syntax for the following operations:

print $hash{'key'} # same as print $webapp->param('key') $hash{'key'} = 3; # same as $webapp->param('key', 3);
However, I would make sure it is really worth implementing because it will add complexity and degrade your application performance.

If you really need to access the values as a hash, perhaps you can first extract all the CGI parameters to a hash like this:

our %hash; my @all_params = $webapp->param(); for my $p (@all_params) { $hash{$p} = $webapp->param($p); # } ... use %hash instead of calling $webapp->param(...) ...

Replies are listed 'Best First'.
Re^2: CGI::Application - alternative to using $self->param?
by friedo (Prior) on Nov 21, 2007 at 00:20 UTC
    Also, the ->param(...) method is read-only - you can't change values of parameters with it.

    Sure you can. It works pretty much just like CGI's param method. This works fine:

    $self->param( key => \%valuahash );

    If you want a hash with all your params, you can get it like this:

    sub some_run_mode { my $self = shift; # note that CGI.pm does the same thing: my @params = $self->param; my %hash = map { $_ => $self->param( $_ ) } @params; }

    That would be a little tedious to do in every runmode, but you could do it in a prerun hook instead.

      Thanks for pointing that out. Shortly after writing that I decided to check it out and re-edited my response accordingly.