As previously mentioned, using a variable that was conditionally defined is not valid Perl, but the compiler does not flag it as an error. I shall suggest alternatives.
The problem can be eliminated from
sub new { my $class = shift; my %self = %{$_[0]} if ref $_[0]; ... }
by writing it as
# Class->new(); # Class->new({ k=>v, ... }); sub new { my $class = shift; my %self = ref $_[0] ? %{$_[0]} : (); ...
Better yet, allow the curlies to be omitted for free.
# Class->new(); # Class->new({ k=>v, ... }); # Class->new( k=>v, ... ); sub new { my $class = shift; my %self = ref $_[0] ? %{$_[0]} : @_; ... }
I always found using the curlies around named args silly. Sounds like a premature optimisation that does little more than make the code noisier.
There's also the following which doesn't allow hash refs at all:
# Class->new(); # Class->new( k=>v, ... ); sub new { my ($class, %self) = @_; ... }
In reply to Re^2: Should "use strict" complain if I use a variable that is not declared?
by ikegami
in thread Should "use strict" complain if I use a variable that is not declared?
by earthman
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |