Home > Software engineering >  what is the difference between @{$value} and @$value in perl
what is the difference between @{$value} and @$value in perl

Time:04-09

Example:

for my $key ( keys %DNS_CSV_FILES){ 
    for my $file (@$DNS_CSV_FILES{$key}){
        print $file; 
    }
}

gives the error: Global symbol "$DNS_CSV_FILES" requires explicit package name (did you forget to declare "my $DNS_CSV_FILES"?) at dns.pl line 41. Execution of dns.pl aborted due to compilation errors.

while

for my $key ( keys %DNS_CSV_FILES){
    for my $file (@{$DNS_CSV_FILES{$key}}){
        print $file; 
    }
}

gives the desired output: file1.txtfile2.txt

CodePudding user response:

@$DNS_CSV_FILES is dereferencing $DNS_CSV_FILES as an array. You don't have a reference scalar named $DNS_CSV_FILES so this fails.

@{$DNS_CSV_FILES{$key}} is dereferencing $DNS_CSV_FILES{$key} as an array. $DNS_CSV_FILES{$key} is accessing a key on the %DNS_CSV_FILES hash.

CodePudding user response:

This

@$DNS_CSV_FILES{$key}

Will from the left side see an array sigil @ followed by a scalar $. This can only be the dereferencing of an array ref. Otherwise the @ is a syntax error. Despite you putting the hash notation at the end. It is a race condition, of sorts. So it will assume that what follows is a scalar, and not a hash value.

When you clarify by adding extra brackets, it becomes clear what is intended

@{   $DNS_CSV_FILES{$key}   }

Whatever is inside @{ } must be an array ref, and $....{key} must be a hash value.

  •  Tags:  
  • perl
  • Related