Hi all, I want pass a hash to subroutine, is that possible
Yes. Usually you would just pass a reference.
sub myfunc { my $href = shift; print $href->{foo}, "\n"; } my %h = ( foo => 'bar' ); myfunc(\%h);
It is possible to pass the whole hash but it gets messy if you want to add arguments later. Some people handle named parameters this way. (Others prefer a hash ref for that too.)
sub myfunc { my %hash = @_; print $hash{foo}, "\n"; } my %h = ( foo => 'bar' ); myfunc(%hash); myfunc( foo => 'baz' );
There is one significant difference between these you should be aware of. In the first example, you are passing a reference to the hash itself. If you would change the hash via the reference within your sub, you would see those changes outside of your sub. In the second example, the line my %hash = @_; makes a copy of the hash. Changes to that copy inside the sub will not be seen outside of the sub. On the other hand, if you have a large hash, making a copy might take a lot of resources.
Edit: Added quote from OP.
-sauoq "My two cents aren't worth a dime.";
In reply to Re: pass a hash to subroutine
by sauoq
in thread pass a hash to subroutine
by benlaw
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |