Gossamer Forum
Quote Reply
map
Hi everyone,

I want to learn how to use the map function. I have a little example where I think it could be used,
Code:
foreach (keys %$link) {
$tags->{"links_link_$_"} = $link->{$_}
};
This takes the hashref $links = { key => value} and maps it to $tags = { links_link_key => value}.

How would I do that using map? I tried, but obviously failed (otherwise I wouldn't be asking....)

Ivan
-----
Iyengar Yoga Resources / GT Plugins
Quote Reply
Re: [yogi] map In reply to
Hi,

What did you try?

Something like this should work:
Code:
my %$tags = map { "links_link_$_" => $link->{$_} } keys %$link;

Last edited by:

Paul: Apr 18, 2002, 6:14 AM
Quote Reply
Re: [Paul] map In reply to
That's exacly what I tried, but it gives me a syntax error...

Ivan
-----
Iyengar Yoga Resources / GT Plugins
Quote Reply
Re: [yogi] map In reply to
Are you sure you didn't insert a comma after } by accident?...I sometimes do that.

Last edited by:

Paul: Apr 18, 2002, 5:57 AM
Quote Reply
Re: [Paul] map In reply to
Yes, very sure. I tried that too...

Ivan
-----
Iyengar Yoga Resources / GT Plugins
Post deleted by Paul In reply to

Last edited by:

Paul: Apr 18, 2002, 6:04 AM
Quote Reply
Re: [yogi] map In reply to
Ok, the following works:

Code:
my %$tags = map { $_ => $link->{$_} } keys %$link;

...but this doesn't:

Code:
my %$tags = map { "links_link_$_" => $link->{$_} } keys %$link;

So it seems it has a problem with the key. Hmm Im gonna have a play about...
Quote Reply
Re: [Paul] map In reply to
I just found out that the following works (strangely enough):
Code:
my %$tags = map { 'links_link_' . $_ => $link->{$_} } keys %$link;

Thanks for your help anyway.

Ivan
-----
Iyengar Yoga Resources / GT Plugins

Last edited by:

yogi: Apr 18, 2002, 6:11 AM
Quote Reply
Re: [yogi] map In reply to
Ok here ya go :)

Code:
my %$tags = map { eval { qq{links_link_$_} } => $link->{$_} } keys %$link;
Quote Reply
Re: [yogi] map In reply to
Hehe the answer to this question was so easy yet at the time I just totally didn't know what I was on about :)

Quote:
my %$tags = map { "links_link_$_" => $link->{$_} } keys %$link;

That's exacly what I tried, but it gives me a syntax error...

It is because perl is trying to evaluate the code as an expression rather than a block, changing it to:

my %$tags = map { +"links_link_$_" => $link->{$_} } keys %$link;

...will get rid of the error :)