Passing array, scalar and hash to subroutine in Perl

arrays, hashmap, perl

Solution

You can use references:

getMsg(\@array, \%hash, $scalar);

sub getMsg {
    my ($aref, $href, $foo) = @_;
    for my $elem (@$aref) {
        ...
    }
}

Note that the assignment you tried:

my (@a, $s, %h) = @_;

Does not work, because `@a` -- being an array -- will slurp up the entire list, leaving `$s` and `%h` uninitialized.

Problem

What's the best way to send multiple arrays, variables, hashes to a subroutine? Simple form, works. ``` my $msg = &getMsg(1,2,3); print $msg; sub getMsg { my($a, $b, $c) = @_; } ``` I am having difficulty with this version and am not sure how to send the data safely to the subroutine without using a global which is not what I want to do. ``` my @array = ('a','b','c'); my $str = "Hello"; my %hash = ( 'a' => ['100','nuts'], 'b' => ['200','bolts'], 'c' => ['300','screws'], ); my $msg = getMsg(@array, $str, %hash); print $msg; sub getMsg { my (@a, $s, %h) = @_; my $MSG; foreach my $x (@a) { $MSG .= "\n$str, $x your hash value = $h{$x}[0] $h{$x}[1]"; } return $MSG } ```

Original source