in reply to Should "use strict" complain if I use a variable that is not declared?

my %self = %{$_[0]} if ref $_[0];

has been deprecated and never really did what you think. See the end of Statement Modifiers in perlsyn about the behaviour or the lack of definedness.

  • Comment on Re: Should "use strict" complain if I use a variable that is not declared?
  • Download Code

Replies are listed 'Best First'.
Re^2: Should "use strict" complain if I use a variable that is not declared?
by ikegami (Patriarch) on Jun 28, 2010 at 17:27 UTC

    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) = @_; ... }
Re^2: Should "use strict" complain if I use a variable that is not declared?
by earthman (Initiate) on Jun 28, 2010 at 11:24 UTC

    Thank you for this very good pointer to the documentation. Here be dragons, indeed.