Search code examples
perlsubroutine

Trouble passing hash and variable to subroutine


I want to pass a hash and a variable to a subroutine:

%HoA = {'1'=>'2'};
my $group_size = 10;

&delete_unwanted(\%HoA,$group_size);

sub delete_unwanted {
    my (%HoA,$group_size) = @_;
    print "'$group_size'\n"
}

But, this prints nothing.


Solution

  • You're passing a hash reference (as you should), so therefore assign it to a scalar in your parameter catching:

    sub delete_unwanted {
        my ($hashref, $group_size) = @_;
    
        print "'$group_size'\n"
    }
    

    If you later want to dereference it, you can my %newHoA = %$hashref;, but that will be a copy of the original hash. To access the original structure, just use the reference: print $hashref->{a_key};.