Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: "map" sometimes uses only the last mapped value

by turo (Friar)
on Apr 18, 2006 at 13:57 UTC ( [id://544061]=note: print w/replies, xml ) Need Help??


in reply to "map" sometimes uses only the last mapped value

Seems to be a problem with references ...

The map operator receives all the elements of the array (x, y, z) and passes all of them correctly to the function f2:

#! /usr/perl -l sub f1 { my ($f) = @_; my @z = ("$f"); for my $d (@z) {return $d} } sub f2 { my ($f) = @_; print "\n*$f*\n" for my $d ("$f") {return $d} } sub f3 { for my $d (@_) {return $d} } print map {f1($_)} qw(x y z); print map {f2($_)} qw(x y z); print map {f3($_)} qw(x y z);
Extrange, is like the function f2, only has been collecting the ref of the $d variable, and when print is going to print the array, it prints the value of the same reference; that is the last 'z' (what's about the scopes!!! arrg)

I have solved the problem using a intermediate variable:

#! /usr/perl -l sub f1 { my ($f) = @_; my @z = ("$f"); for my $d (@z) {return $d} } sub f2 { my ($f) = @_; for my $d ("$f") {my $a=$d; return $a} } sub f3 { for my $d (@_) {return $d} } print map {f1($_)} qw(x y z); print map {f2($_)} qw(x y z); print map {f3($_)} qw(x y z);

cheers

perl -Te 'print map { chr((ord)-((10,20,2,7)[$i++])) } split //,"turo"'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://544061]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (1)
As of 2024-04-25 03:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found