Deano Deano - 7 months ago 11
Perl Question

Perl - How to create variables when looping through @_ variables

I'm passing the following hash to a subroutine

$VAR1 = {
'password' => 'abc123',
'IP' => '172.18.18.122',
'port' => '8080',
'username' => 'sensor1'
};


and I'm getting these results when I do user Dumper with
@_
variable

print Dumper(@_);


How can I loop through value pairs and create variables $IP,$username ..etc

I have created

my $variables;
foreach my $key ( keys @_) {
my $key = @_->{$key}\n";
}


but I always get an error.

Type of arg 1 to keys must be hash (not array dereference) at /perl/modules/Sentinel/Api.pm line 17, near "@_) "
Compilation failed in require at agent line 9.
BEGIN failed--compilation aborted at agent line 9.

Answer

Generally speaking, keys should be of the form

keys( %something )
      ^
      |

@_ contains a reference to a hash, so you could use the following:

keys( %{ $_[0] } )

Instead, we could give it a name:

my ($hash) = @_;

for my $key ( keys( %$hash ) ) {
   my $val = $hash->{$key};
   ...
}

If the number of references is variable:

for my $hash ( @_) {
   for my $key ( keys( %$hash ) ) {
      my $val = $hash->{$key};
      ...
   }
}
Comments