Pass hash to subroutine?

D

Davy

Hi all,

How to pass hash to subroutine?
And my code list below(it seems the hash has not been passed to sub??):


Code:
#!/usr/local/bin/perl
%mc_mode_hash = ( "00" => "mc_mode_0",
"01" => "mc_mode_1",
"10" => "mc_mode_2");
my $my_cnt = 1;
$my_cnt = &init_cnt_ref(%mc_mode_hash);
print ("my_cnt is $my_cnt \n");
sub init_cnt_ref(\%)
{
#my (%hash0) = %{(shift)};
my %hash0 = %_ ;
my $cnt = 0;
foreach $mc_mode ( values(%hash0))
{
print "mc_mode is $mc_mode \n";
$cnt ++;
}
return $cnt;
}


Thanks!
Davy
 
P

Paul Lalli

Davy said:
How to pass hash to subroutine?
And my code list below(it seems the hash has not been passed to sub??):

No, it was passed just fine. You just didn't grab it in the subroutine
itself.

Code:
#!/usr/local/bin/perl

You forgot:
use strict;
use warnings;

Put these at the top of *every* script you write. They find 95% of the
errors you're likely to make - including the one you made in this
program.
%mc_mode_hash = ( "00" => "mc_mode_0",

What is the point of the _hash suffix of this variable name? The %
already identifies this as a hash.
"01" => "mc_mode_1",
"10" => "mc_mode_2");
my $my_cnt = 1;
$my_cnt = &init_cnt_ref(%mc_mode_hash);

Why are you calling your subroutine with the & prefix? Do you know
what two side effects that causes? Do you want those side-effects? If
not, leave it off.
print ("my_cnt is $my_cnt \n");
sub init_cnt_ref(\%)
{
#my (%hash0) = %{(shift)};

This would have worked correctly, had you not made the mistake that
'use warnings' would have told you about. Put that statement in, and
you'll see what you did wrong.
my %hash0 = %_ ;

This is nonsense, as %_ is not a special variable. Arguments are
passed in to a subroutine via the local @_ array.

my %hash0 = @_;
my $cnt = 0;
foreach $mc_mode ( values(%hash0))
{
print "mc_mode is $mc_mode \n";
$cnt ++;
}
return $cnt;
}


Paul Lalli
 
D

Davy

Hi,

Thanks!

I have used "use *" as you said. And find I should pass \% to
subroutine. All work ok!

Best regards,
Davy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,189
Members
46,735
Latest member
HikmatRamazanov

Latest Threads

Top