Search code examples
arraysperlhashsubroutine

How to pass a hash of arrays in a subroutine?


I am kinda new to perl and I want to ask how I can pass a hash of arrays in a subroutine. More specifically, I have a hash of arrays

my %records = (a => [ qw/ A B C / ], b => [ qw/ C D E A / ], c => [ qw/ A C E / ],);

and I want to apply

use Array::Utils qw(:all)
#unique union
my @unique = unique(array1, array2, ..., arrayX);

to all the arrays in the hash. I am trying to make a subroutine which will have as input the hash and return the unique union of all the arrays in it. Any help will be much appreciated.

Thanks in advance, Thanos


Solution

  • You have to pass its values (which are array references) and dereference them (as you can see below, inside the map function, by prepending the @ symbol):

    use Array::Utils qw(:all);
    my %records = (a => [ qw/ A B C / ], b => [ qw/ C D E A / ], c => [ qw/ A C E / ],);
    my @unique = unique(map {@$_} values %records);
    print join(' ',@unique); #will print "A B C D E"