Re: map sub to list?
by BrowserUk (Patriarch) on Sep 09, 2013 at 16:50 UTC
|
chr defaults to using $_, so use: @a = map f( $_ ), @numbers;.
Or define f() to default to $_:
sub f(_){ $_[0]+1 };
Now my @a = map f, @numbers; works.
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] [d/l] [select] |
|
Thanks to everybody who replied! I think I've got it. When writing
@a = map f( $_ ), @numbers;
this is a case of map BLOCK LIST (as opposed to map EXPR LIST) right?
| [reply] [d/l] |
|
No, using the comma makes it a case of EXPR, LIST.
| [reply] |
|
|
|
|
|
Re: map sub to list?
by toolic (Bishop) on Sep 09, 2013 at 16:48 UTC
|
How is one different from the other?
perldoc -f ord does not require you to explicitly pass an argument to it, but your user-defined sub f requires you to pass an argument to it.
| [reply] [d/l] |
Re: map sub to list?
by Arunbear (Prior) on Sep 09, 2013 at 16:58 UTC
|
If you're just adding 1 to each element then defining a separate sub is overkill:
% perl -de0
Loading DB routines from perl5db.pl version 1.32
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(-e:1): 0
DB<1> @a = (1, 2, 3)
DB<2> x @a
0 1
1 2
2 3
DB<3> x map { $_ + 1 } @a
0 2
1 3
2 4
DB<4> q
%
| [reply] [d/l] |
Re: map sub to list?
by LanX (Saint) on Sep 09, 2013 at 16:59 UTC
|
DB<100> sub f { return $_ + 1 };
DB<101> map f, 1..3
=> (2, 3, 4)
DB<102> map &f, 1..3
=> (2, 3, 4)
Cheers Rolf
( addicted to the Perl Programming Language)
| [reply] [d/l] |
Re: map sub to list?
by Laurent_R (Canon) on Sep 09, 2013 at 17:12 UTC
|
Don't use function prototypes unless you know how and, more importantly, why. This is not needed here and is the main cause of your problem.
| [reply] |
|
I've tried removing the prototype, of course; but actually the main cause of the problem was relying on an argument as opposed to $_, right? I prefer functional style as much as possible, coming from a Lisp background and all that :)
| [reply] |
|
Yes. Assuming you want to keep the overkill of a function, you could either change the relevant line to:
sub f{ return $_ + 1 };
or pass the $_ as an argument to the function:
use strict; use warnings;
sub f{ return $_[0] + 1 };
my @a = (1, 2, 3);
print join " ", map (f($_), @a);
I have added the join because you like functional programming. But the more common way to do such things is illustrated in the following Perl one-liner:
$ perl -e 'print join " ", map {$_ + 1} 1..4'
2 3 4 5
Talking of functional programming, note that the block of code after the map (the {$_ + 1} part) can be regarded as an anonymous function being applied by map onto each input element.
| [reply] [d/l] [select] |
|
|