Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Passing hashes to subroutines

by rbi (Monk)
on Jun 08, 2004 at 08:41 UTC ( #362239=perlquestion: print w/replies, xml ) Need Help??
rbi has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to pass different types of variables to a subroutine using named arguments, but I don't understand how it works for hashes. I'm sure I'm missing some basic concept...
I made some trials in the following, but only the first call to dummy works.
Could someone provide me some clue ?
Thank you in advance.
use strict; my %hash = {a=>'A', b =>'B'}; my @array = [1,2,3]; my $scalar = 'This is a scalar'; dummy(array=>@array, scalar=>$scalar, hash=>{a=>'A', b =>'B'}); dummy(array=>@array, scalar=>$scalar, hash=>%hash); my $hashref = \%hash; dummy(array=>@array, scalar=>$scalar, hash=>$hashref); sub dummy { my %args = @_; my @a = @{$args{array}}; my %h = %{$args{hash}}; my $s = $args{scalar}; print "scalar is: $s\n", 'array is: ', join(',', @a),"\n", "hash is:\n", map "$_ => $h{$_}\n", keys %h; print "--------\n"; }

Replies are listed 'Best First'.
Re: Passing hashes to subroutines
by cchampion (Curate) on Jun 08, 2004 at 08:59 UTC

    Your declaration for array and hash are wrong. If you use warnings you'll see why.

    This modified code should do what you want:

    #!/usr/bin/perl -w use strict; my %hash = (a=>'A', b =>'B'); # parens, not braces my @array = (1,2,3); # parens, not brakets my $scalar = 'This is a scalar'; # Pass an array REFERENCE dummy(array=>\@array, scalar=>$scalar, hash=>{a=>'A', b =>'B'}); dummy(array=>\@array, scalar=>$scalar, hash=>\%hash); my $hashref = \%hash; dummy(array=>\@array, scalar=>$scalar, hash=>$hashref);


Re: Passing hashes to subroutines
by blueAdept (Beadle) on Jun 08, 2004 at 14:17 UTC
    Hashes must be passed by reference, which means they're nothing more than a single scalar value (in terms of an arguement to a subroutine) If you don't pass its reference, instead just do foo(%hash) then what you're really passing in is an even paired list. HTH.

    use strict; use warnings; my %hash1; $hash1{hello} = "world!"; foo(\%hash1); foo( { hello => 'world!!' } ); sub foo { my %hash2 = %{$_[0]}; print "hello " . $hash2{hello} . "\n"; } #output #hello world! #hello world!!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://362239]
Approved by integral
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2017-08-23 11:21 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (350 votes). Check out past polls.