Reputation: 1343
The code is getting a similar warning as in
Why does this code throw a "Useless use of anonymous hash ({}) in void context" warning.
The warning does not come out until I use strict. And when I try to use this code in a much bigger subroutine that use strict it fails miserably so I like to figure out why the code below gives me this warning when I use strict.
#!/usr/bin/perl
use strict;
use warnings;
sub foo {
my %args=@_;
my %defaults=(my $config=>'kconfig', my $mem=>'kmem', my $baz=>7);
foreach (keys %defaults) {
defined ($args{$_}) || {$args{$_}= $defaults{$_}} ;
print $_ ," - ",$args {$_},"\n";
}
}
&foo (bar=>"1");
Upvotes: 3
Views: 1929
Reputation: 118665
{$args{$_}= $defaults{$_}}
is where the error warning is occuring. It looks like you are trying to use {...}
to give the assignment precedence over the ||
comparison, but { ... }
are used to define hash references (or sometimes code blocks, but that's not how they are interpreted in this context).
Since this is Perl, there are several ways to rewrite this.
defined($args{$_}) || ($args{$_}=$default{$_}); # () are good for grouping
$args{$_} //= $defaults{$_}; # requires Perl v5.10 or better
defined($args{$_}) or $args[$_} = $default{$_}; # or has lower prec than ||
defined($args{$_}) || do { $args{$_}=$default{$_} }; # {} is a code block with do
$args{$_}=$default{$_} unless defined $args{$_};
my %defaults=(my $config=>'kconfig', my $mem=>'kmem', my $baz=>7);
also looks horribly wrong. my
is used to declare a new variable in the current scope, and the initial value of the variable will be undef
. That makes this line equivalent to
my %defaults = (undef, 'kconfig', undef, 'kmem', undef, 7);
From this context, I figure that %defaults
is supposed to store default arguments for three required parameters, and is better written as
my %defaults = (config => 'kconfig', mem => 'kmem', baz => 7);
Upvotes: 8