Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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:

Hello,
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"; }

Comment on Passing hashes to subroutines
Select or Download Code
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);

    HTH

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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://362239]
Approved by integral
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2014-08-22 11:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (156 votes), past polls