I’m having trouble understanding how references work with hashes in subs.
In this code, I try to change %config inside the handleOptions() subroutine :
sub handleOption;
my %config = ( gpg => "",
output => "",
pass => "",
host => "",
type => "");
handleOptions(\%config);
print "\n";
print Dumper \%config;
sub handleOptions
{
my ($gpgpath,$type,$pass,$host);
my $pConfig=@_;
GetOptions ("gpg=s" => \$gpgpath,
"type=s" => \$type,
"host=s" => \$type,
"pass=s"=>\$pass);
$pConfig->{'gpg'} = $gpgpath;
$pConfig->{'type'} = $type;
$pConfig->{'pass'} = $pass;
$pConfig->{'host'} = $host;
print Dumper %$pConfig;
}
Here is the output when I give --gpg='/home/daryl/gpg/pass.gpg to the options in cli :
$VAR1 = 'pass';
$VAR2 = undef;
$VAR3 = 'gpg';
$VAR4 = '/home/daryl/gpg/pass.gpg';
$VAR5 = 'type';
$VAR6 = undef;
$VAR7 = 'host';
$VAR8 = undef;
$VAR1 = {
'pass' => '',
'gpg' => '',
'type' => '',
'output' => '',
'host' => ''
};
How should i proceed ?
If you were to
use strictanduse warnings, you’d see an error message about using a scalar as a hash reference. That would tip you off that the problem is in this line:You’re assigning a scalar context of the array
@_to the variable$pConfig. What this means is that$pConfigis storing the number of elements in the array@_.Instead, you can do:
my ($pConfig) = @_;as KerrekSB suggests, or:my $pConfig = shift;(whichshifts from@_automatically)Take a look at
perldoc perldatafor more information on calling non-scalars in scalar context. Also, unless you’re writing a one-liner or a short throw-away script, make sure to alwaysuse strictanduse warnings.