in reply to Re: Hash reference as a parameter
in thread Hash reference as a parameter

I am a beginner in Perl. Please correct me if I am wrong!
I want to do something like the following, so that I can alter only some values of the hash and call the function again and again. I am not sure whether the same thing can be done using a 'list' as suggested in the previous post.
#!/usr/bin/perl use strict; use Data::Dumper; my %input = {foo => 'bar', oof => 'wha'}; my_sub(\%input); $input{foo} = 'bar1'; my_sub(\%input); sub my_sub { my $ref = shift; my %args = ( foo => 'oop', pah => 'meh', oof => 'off', %{$ref} ); warn Dumper(\%args); }

Replies are listed 'Best First'.
Re^3: Hash reference as a parameter
by saberworks (Curate) on Sep 12, 2005 at 21:45 UTC
    Hrm, interesting question. It seems more like you want a global hash which gets reset to the default values each time the function is called with the exception of the values you pass in. I still don't think a reference is the way to go, but if it works, meh. What about this:
    #!/usr/bin/perl use strict; use Data::Dumper; my %hash = (); my_sub(foo => 'bar', oof => 'wha'); my_sub(pah => 'eek'); sub my_sub { %hash = ( foo => 'oop', pah => 'meh', oof => 'off', @_ ); warn Dumper(\%hash); }
      Thanks for your time. But this is not the solution that I wanted!

      My idea is very simple. If the user creates the input parameters as a hash then he can alter the hash at any time and call the function. This is what I mean by the following statements.
      my %input = {foo => 'bar', oof => 'wha'}; my_sub(\%input); $input{foo} = 'bar1'; my_sub(\%input);
        So, in this case the code I posted first works fine, right? What I am confused about is why you want to pass things like this:
        my_sub(\%hash);
        instead of like this:
        my_sub(%hash);
        But, it really doesn't matter, if the solution works for you just use it :)

        Hrm, do you want the changes to be cumulative or to reset each time?