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

Hello!

I am using CGI.pm's hook call back and I need to use a variable defined in my (the calling) package. It's getting lost and I am not sure how to define it (without declaring it before use strict, or is that the only way??).

So, this is just the relevant code below. $test gets printed in go() but lost during the hook() callback (I understand why, just not sure what the proper way of getting around this is).

use strict; use CGI; our $test = "Big test"; go(); sub go { my $q = CGI->new(\&hook); print $test; } sub hook { my ($filename, $buffer, $bytes_read, $data) = @_; print $test; }

Replies are listed 'Best First'.
Re: Making a variable available to another package in a call back
by GrandFather (Saint) on Nov 19, 2008 at 21:50 UTC

    Use an anonymous sub:

    use strict; use CGI; our $test = "Big test"; go(); sub go { my $q = CGI->new(sub {return hook (\$test, @_);}); print $test; } sub hook { my ($test, $filename, $buffer, $bytes_read, $data) = @_; print $$test; }

    Update: or, for a fully worked sample:

    use strict; use warnings; package Foo; sub new { my ($class, $callback) = @_; return bless {callback => $callback}, $class; } sub doIt { my ($self) = @_; return $self->{callback}->(); } package main; my $test = "Big test"; my $foo = Foo->new (sub {return hook (\$test);}); $foo->doIt (); print $test; sub hook { my ($test, $filename, $buffer, $bytes_read, $data) = @_; $$test .= ': success'; }

    Perl reduces RSI - it saves typing
Re: Making a variable available to another package in a call back
by ccn (Vicar) on Nov 19, 2008 at 22:02 UTC

    The variable is not lost. Seems your callback just not called.

    Update: Your callback is not called in the code you given. Anyway, if you specify package for $test it is not lost.

    sub hook { my ($filename, $buffer, $bytes_read, $data) = @_; print $::test; }