470,581 Members | 2,438 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,581 developers. It's quick & easy.

Hash as a function argument.. plz help!

Hi all,
I have a problem with a snippet of code. I'm trying to pass a hash as an
argument to a function. Below is some test code:

--- snip snip
use strict;

my %map = {
1 => 'one',
2 => 'two',
3 => 'three',
};

sub fun {
my $what = shift;
my %hash = @_;

print ("$what: ");
foreach my $k (keys (%hash)) {
print (" [$k]=[$hash{$k}]");
}
print ("\n");
}

# Why won't this work..
fun ("whatever", %map);

# But this will ?!
fun ("again",
'a' => 'first char', 'b' => 'second');
--- snip snip

What am I doing wrong (obviously near the comment mark "why won't this
work")? Any and all help will be appreciated!

Thanks in advance,
--
Karel Kubat <ka***@e-tunity.com, ka***@qbat.org>
Phone: mobile (+31) 6 2956 4861, office (+31) (0)38 46 06 125
PGP fingerprint: D76E 86EC B457 627A 0A87 0B8D DB71 6BCD 1CF2 6CD5

From the duffynitions collection:
Mistress: Something between a mister and a mattress.

Jul 19 '05 #1
2 6278
> # Why won't this work..
fun ("whatever", %map);

# But this will ?!
fun ("again",
'a' => 'first char', 'b' => 'second');
--- snip snip

What am I doing wrong (obviously near the comment mark "why won't this
work")? Any and all help will be appreciated!

You should declare your hash by ()-signs and not by {}-signs. In your code:

my %map = (
1 => 'one',
2 => 'two',
3 => 'three',
);

Regards,
Bart
Jul 19 '05 #2
Bart Van der Donck <ba**@nijlen.com> wrote in comp.lang.perl.misc:
# Why won't this work..
fun ("whatever", %map);

# But this will ?!
fun ("again",
'a' => 'first char', 'b' => 'second');
--- snip snip

What am I doing wrong (obviously near the comment mark "why won't this
work")? Any and all help will be appreciated!

You should declare your hash by ()-signs and not by {}-signs. In your code:

^^^^^^^ my %map = (
1 => 'one',
2 => 'two',
3 => 'three',
);


That's not declaration, it's assignment. The declaration is "my %map".

Sorry for the nitpick, but "declaration" and "assignment" (or
"initialization") are often confused. We have an ongoing thread
where this lead to a misunderstanding.

Anno
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Karel Kubat | last post: by
34 posts views Thread by pembed2003 | last post: by
7 posts views Thread by Diane | last post: by
21 posts views Thread by Johan Tibell | last post: by
11 posts views Thread by Douglas Dude | last post: by
139 posts views Thread by ravi | last post: by
3 posts views Thread by giloosh | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.