Search code examples
perlperl-data-structures

Get hash of arrays content inside a subroutine


I have a hash of array like this which i want to use inside a subroutine. I pass it by reference to this subroutine like the &sub(\%hash) and inside sub i do this print Dumper $_[0] and this is my output :

$VAR1 = {
      'key1' => [
                              'value1',
                              'value2'
                            ],
      'key2' => [
                                          'foo',
                                          'bar'
                                        ]
    };

What is the proper way get the content of all array values into 2 separate arrays inside my subroutine like this :

my @ones ; my @tows ;
print "@ones" ;
print "\n"; 
print "@tows";

And get this in the output

value1 foo
value2 bar

Solution

  • Don't call your subroutine with a &. It'll just confuse you at some point and hasn't been necessary for almost twenty years.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use 5.010;
    
    my %hash = (
      key1 => [
        'value1',
        'value2'
      ],
      key2 => [
        'foo',
        'bar'
      ]
    );
    
    print_vals(\%hash);
    
    sub print_vals {
      my ($hashref) = @_;
    
      # $hashref->{key1} is a reference to an array
      # therefore @{$hashref->{key1}} is an array
      my @arr1 = @{$hashref->{key1}};
      my @arr2 = @{$hashref->{key2}};
    
      # $#arr1 is the last index in @arr1
      for (0 .. $#arr1) {
        say "$arr1[$_] $arr2[$_]"
      }
    }