I have the following perl code:
@searchInfo = ();
sub main()
{
processCmdLine();
foreach my $info ( @searchInfo )
{
print "Search field: " . $info{field} . "\n";
print "Search value: " . $info{value} . "\n";
}
}
sub processCmdLine()
{
while(@ARGV > 1)
{
$rec = {};
$rec{field} = shift(@ARGV);
$rec{value} = shift(@ARGV);
print "$info{field} = $info{value}\n";
push @searchInfo, $rec;
}
}
When I run this, with a command like: script.pl f1 v1 f2 v2, I get the following output
f1 = v1
f2 = v2
Search field:
Search value:
Search field:
Search value:
I’m basing the code on this tutorial.
What is the reason why the hashes inside the array have empty values?
Always use
use strict; use warnings;!!! It would tell you you’re accessing a hashes named%infoand%rec, but you don’t have such variables.Hash values are scalars. As such, they cannot contain hashes. This can be approximated by using references to hashes. You seem to realise this by using
$rec = {};, but then you never use that variable again.Fix:
Cleaner fix:
Don’t forget to fix the fetcher too:
But why are you creating whole bunch of hashes with one key?! Did you perhaps mean to do:
Then the fetcher would be