Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

pass a hash to subroutine

by benlaw (Scribe)
on Nov 07, 2005 at 08:42 UTC ( [id://506329]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

benlaw has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I want pass a hash to subroutine, is that possible
#! perl -w %a = (qw{ good orange bad apple} ); TEST(%a); sub TEST{ my %h = $_[0]; foreach (keys %h){ print $_; } }
Thanks

Replies are listed 'Best First'.
Re: pass a hash to subroutine
by sauoq (Abbot) on Nov 07, 2005 at 08:45 UTC
    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.";
    
Re: pass a hash to subroutine
by g0n (Priest) on Nov 07, 2005 at 08:47 UTC
    As sauoq said, you could use a reference, which is probably the best way. You could also do this though:
    #! perl -w %a = (qw{ good orange good apple} ); TEST(%a); sub TEST{ my %h = @_; foreach (keys %h){ print $_; } }

    Note using @_ where you had used $_[0] - that converts the entire array of parameters into a hash.

    This is because the function receives a list of param, value, param, value.., which is stored in @_. By doing %h = @_; you put this into a hash with the first, third, fifth etc values as keys, and the second, fourth, sixth etc as values.

    --------------------------------------------------------------

    "If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."

    John Brunner, "The Shockwave Rider".

      Thanks for all "rapid" reply, the case solved

      But once more, if i want pass 2 or more hashes to subroutine, is it the same?

        If you want to pass 2 or more hashes to a subroutine, you really need to use references. Have a look at perldoc perlref, but basically the syntax is:

        my %hashA = ( orange=>'good', apple=>'bad' ); my %hashB = ( here=>'today', gone=>'tomorrow' ); myfunction(\%hashA,\%hashB); # send references to the hashes sub myfunction { my $hashrefA = shift; # (or $_[0]) my $hashrefB = shift; # (or $_[1]) my %hashA = %$hashrefA; # treat the refs as hashes and my %hashB = %$hashrefB; # copy the contents $hashA{extravalue} = "change seen in the subroutine only"; $hashrefA->{extravalue} = "change seen in the main program"; }

        Following on from sauoqs comments, with that syntax, %hashA and %hashB in the subroutine are still copies of the original hashes. If you want to manipulate the original hashes and have the changes seen by the main part of the program, you will have to manipulate the hashrefs. I've included an example of each in the snippet above. If all you want to do is e.g. print them out, the copies might be less unwieldy to work with, if you're not familiar with reference syntax.

        --------------------------------------------------------------

        "If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."

        John Brunner, "The Shockwave Rider".

        But once more, if i want pass 2 or more hashes to subroutine, is it the same?
        It was already in my answer, (although I minimally updated it silently for added clarity). Minimal example using a prototype:
        #!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub foo (\%\%) { Dumper @_; } my %a=(foo => 1, bar =>2); my %b=(%a, bax => 3); print foo %a, %b; __END__
Re: pass a hash to subroutine
by blazar (Canon) on Nov 07, 2005 at 09:26 UTC

    Yes, it's possible. But it depends on what you actually want to do. If you just want to do what you show in your example, then

    my %h=@_; # is enough!

    But if you also want to modify the hash you pass in, or if you want to pass a few params of which one (or more) happens (happen) to be a hash, then as others already pointed out, you have to use a reference. You can also use a prototype, as explained in perldoc perlsub to have perl doing this for you. But regard that as a somewhat advanced technique and be sure to have understood the docs if you want to apply it...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://506329]
Approved by monkfan
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.