Passing hash reference to multiple functions in Perl
I have following code in Perl where a hash reference is passed from main function to func1 and then to func2. In func2 hash is updated. I want to access the updated hash in main function. Also there is a while loop in main function and i am expecting the hash should be updated during every iteration. The code might not look logical, but i have just written the skeleton of the code. I always get empty hash when i try to print the hash in main function
sub main {
my %hash1;
while (some condition)
{
my $i=0;
if($i==0)
开发者_Python百科 {
func1($i,\%hash1);
$i=1;
}
else
{
func1($i,\%hash1);
$i=0;
}
}
foreach my $a (keys %hash1)
{
print "$hash1{$a}";
}
}
sub func1
{
my ($i,$hash1)=@_;
----
if($i==0)
{
func2($hash1);
}
}
sub func2
{
my ($hash2)=@_;
$hash2->{key1}=1;
$hash2->{key2}=2;
}
Ah, I see. You think it's not printing anything as a result of the hash's being empty. But it's really not printing anything because you're not giving it anything to run. You're giving it stuff to compile, but nothing to run.
sub main
means nothing in Perl. In order to get that to run, you have to put somewhere on your mainline main();
Then provided that you comment out the ---
on line 25, you'll get the output you expect.
This is why printing stuff out yourself is either 1) a bit more typing, or 2) not reliable. You saw nothing and thought our hash was empty. When really, the code never even got to the declaration. So, here's a hint, on the command line:
cpan Smart::Comments
And then, in your code:
use Smart::Comments;
...
### %hash1
That way an empty hash looks like this:
### %hash1: {}
And the one that you expect, looks like this:
### %hash1: {
### key1 => 1,
### key2 => 2
### }
Without calling the main
sub, your output looks like this:
(yes, it is blank)
Otherwise, there is nothing wrong with your passing the hash.
精彩评论