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?
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);
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;
看起来,串联就是答案:
my $str = join("\n", map "x(".$c++.") := $_;", @a);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.