Initializing a hash link in perl

The following Perl code prints Value:0 . Is there any way to fix this, except by adding a dummy key to the hash before the hash link is passed to the routine?

 #!/usr/bin/perl use warnings; use strict; my $Hash; #$Hash->{Key1} = 1234; Init($Hash); printf("Value:%d\n",$Hash->{Key}); sub Init { my ($Hash) = @_; $Hash->{Key}=10; } 
+4
source share
2 answers

Initialize an empty hash link.

 #!/usr/bin/perl use warnings; use strict; my $Hash = {}; Init($Hash); printf("Value:%d\n",$Hash->{Key}); sub Init { my ($Hash) = @_; $Hash->{Key}=10; } 
+3
source

I know that the answer has already been accepted, but I decided it was worth explaining why the program acted in this way in the first place.

A hash is not created until the second line of the Init function ( $Hash->{Key}=10 ), which automatically creates a hash and stores the link in the $Hash scanner. This scalar is local to the function and has nothing to do with the $Hash variable in the body of the script.

This can be changed by changing the way the Init function processes its arguments:

 sub Init { my $Hash = $_[0] = {}; $Hash->{'Key'} = 10; } 
+2
source

Source: https://habr.com/ru/post/1500638/


All Articles