Search code examples
perlhashperl-data-structures

What's the best practise for Perl hashes with array values?


What is the best practise to solve this?

    if (... ) 
   { 
    push (@{$hash{'key'}}, @array ) ; 
     }
    else 
     {
     $hash{'key'} =""; 
 }

Is that bad practise for storing one element is array or one is just double quote in hash?


Solution

  • I'm not sure I understand your question, but I'll answer it literally as asked for now...

    my @array = (1, 2, 3, 4);
    my $arrayRef = \@array;     # alternatively: my $arrayRef = [1, 2, 3, 4];
    
    my %hash;
    
    $hash{'key'} = $arrayRef;   # or again: $hash{'key'} = [1, 2, 3, 4]; or $hash{'key'} = \@array;
    

    The crux of the problem is that arrays or hashes take scalar values... so you need to take a reference to your array or hash and use that as the value.

    See perlref and perlreftut for more information.


    EDIT: Yes, you can add empty strings as values for some keys and references (to arrays or hashes, or even scalars, typeglobs/filehandles, or other scalars. Either way) for other keys. They're all still scalars.

    You'll want to look at the ref function for figuring out how to disambiguate between the reference types and normal scalars.