I'm looking at using Attribute::Handlers as the basis for a debugging output system in some code I'm writing. So far, I have something like this:
use Attribute::Handlers; use vars qw($DEBUG); $DEBUG = 0; use constant { PKG => 0, SYMBOL => 1, CODE => 2, ATTR => 3, DATA => 4, PHASE => 5, }; sub Debug :ATTR { my ($symbol, $code, $level) = @_[SYMBOL, CODE, DATA]; $level = $level ne '' ? $level : $DEBUG ; my $name = join '::', *{$symbol}{PACKAGE}, *{$symbol}{NAME}; no warnings 'redefine'; *{$symbol} = sub { my @output = $code->(@_); if ( $level >= 2 ) { warn sprintf "DEBUG: entering %s(%s)\n", $name, ($level >= 3 ? "@_" : ''); } return @output; }; } sub somesub :Debug { # Do something. } sub othersub :Debug(3) { # Do some other thing. }
[download]
One part of this feels inelegant to me, namely:
$level = $level ne '' ? $level : $DEBUG ;
[download]
It has been a while since I was heavily into Perl, so I'm wondering if I'm just forgetting some prettier way to do it... but it keeps nagging at me every time I look at that chunk of code. Anybody know a nicer way to assign a value to a variable only if it is currently NULL?
$level ||= $DEBUG;
[download]
doesn't work, presumably because a null string evaluates to a true value. But that has the flavor I'm looking for.