http://www.perlmonks.org?node_id=1002246


in reply to Passing a variable recursively

The closest thing to what you describe would be to make "PrintToScreen" a singleton object. Your new method would be something like:

my $instance; sub new { my ($class, $loglevel) = @_; $instance ||= do { print "$class $VERSION started with loglevel $loglevel\n" if $loglevel >= 3; bless { _usersetloglevel => $loglevel }, $class; }; }

That way, when your code calls PrintToScreen->new it will always return the same object, at the same loglevel.

Now, it needs to be said that singletons are generally considered code smell - i.e. a sign of poorly thought out code. There are valid use cases for them, but not many. Using a singletons for logging will come back to bite you when you decide you'd like for part of your code (perhaps the network interaction but, say) to be logged in great detail, but not the rest of your code. (Perhaps because you're trying to figure out a bug in the networking stuff without being distracted by hundreds of irrelevant messages from parts of the system you know are working well.)

Better for your logger to be a normal class so you can do:

my $network_connection = NetworkConnection->new; $network_connection->set_logger( PrintToScreen->new(3) ); my $database_connection = DatabaseConnection->new; $database_connection->set_logger( PrintToScreen->new(1) );

See also: Stack Exchange: Why is Global State so Evil?

PS: not sure why you're using "recursively" in your message title. Recursion in computer science is when a function (directly or not) calls itself. A quick example of recursion to implement integer multiplication using just addition and subtraction:

use strict; use warnings; sub multiply_integers { die "two positive integers!\n" if @_ != 2 || grep { not /^[1-9][0-9]*$/ } @_; my ($x, $y) = @_; return $x if $y == 1; return $x + multiply_integers($x, $y-1); } print multiply_integers(7, 6), "\n";
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'