Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

what I'm doing now is

sub foo { my $self = shift; $self->query->param('id'); if (!$id) {return $self->get_id();} #get_id returns a web page that prompts the user for an id #this is all running in mod_perl, with CGI::Application my $obj = $self->get_obj($id); #else do foo kinda stuff with $obj }
But since I have many foo like sub's I'd like to do something like...

sub foo { my $self = shift; my $obj = $self->init; #do foo kinda stuff with $obj } sub init { my $self = shift; $self->query->param('id'); if (!$id) {return $self->get_id();} my $obj = $self->get_obj($id); return($obj); }
Which wont work because init might return an object to foo (as $obj) or HTML to my C::A (as the output of get_id). I could check the return value of init and act accordingly but I'd rather not. So the question is how do I get the return $self->get_id() in init to return to C::A and not just bounce back to foo?

Replies are listed 'Best First'.
Re: controlling what is returned, where.
by Joost (Canon) on Jul 19, 2005 at 18:13 UTC
    Depending on the rest of the code, you might be able to stuff the
    my $id = $self->query->param('id'); $self->param("object") = $self->get_obj($id) if $id;
    in the setup() method.

    Then you "only" need to do

    sub foo { my $self = shift; my $object = $self->param("object") or return $self->get_id(); # ... the rest }
    If you *always* need that object, you might do
    sub cgiapp_prerun { # ... my $id = $self->query->param('id'); if (!$id) { return $self->prerun_mode('get_id'); } $self->param("object") = $self->get_obj($id); # ... }

    which will automatically run the get_id mode unless an id is specified, so all other modes can be certain the object is available in $self->param("object").