Reputation: 1096
I'd like to use an incremented index in Perl, in the map function. The code I have is:
use strict;
my $ord = "46.15,18.59,47.45,21.14";
my $c = 1;
my @a = split(",",$ord);
my $str = join("\n", map "x($c++) := $_;", @a);
print $str;
This outputs:
x(1++) := 46.15;
x(1++) := 18.59;
x(1++) := 47.45;
x(1++) := 21.14;
Instead of the x(1++), I would like x(1), x(2), etc.
How can I reach it?
Upvotes: 1
Views: 962
Reputation: 98398
Instead of mapping the array, you can map your count, and not need a separate variable:
my $str = join("\n", map "x($_) := $a[$_-1];", 1..@a);
Or, to include a trailing newline:
my $str = join('', map "x($_) := $a[$_-1];\n", 1..@a);
Upvotes: 6
Reputation: 386331
Your problem has nothing to do with map
. You placed Perl code inside a string literal and hoped it would get executed.
Replace
map "x($c++) := $_;",
with
map { ++$c; "x($c) := $_;" }
Also, you are missing a trailing newline. Fixed:
my $str = join "", map { ++$c; "x($c) := $_;\n" } @a;
print $str;
or
print map { ++$c; "x($c) := $_;\n" } @a;
Upvotes: 5
Reputation: 1096
It seems, that concatenating is the answer:
my $str = join("\n", map "x(".$c++.") := $_;", @a);
Upvotes: 0