1

Is it possible to use the ++ operator inside a string interpolation? I've attempted the following:

my $i = 0;
foreach my $line (@lines) {
    print "${i++}. $line\n";
}

but I get Compile error: Can't modify constant item in postincrement (++)

2
  • Along with what ikegami said in his answer, you can also use printf(): printf("%d. %s\n", $i++, $line); Commented Jul 24, 2017 at 16:49
  • 1
    @ikegami's is the way to go, but to directly answer your question "Is it possible to use the ++ operator inside a string interpolation?" here a nasty trick I won't admit I even muttered: print "@{[ $i++ ] }. $line\n" (it's similar to @dgw's one, which has been written while I was editing this comment) Commented Jul 24, 2017 at 16:53

2 Answers 2

6

Bareword i is equivalent to "i", so you are doing "i"++.

You want:

print($i++, ". $line\n");

Simpler:

print("$i. $line\n");
++$i;

A good way to embed values into a string is sprintf/printf.

printf("%d. %s\n", $i++, $line);

Note that use strict disallows barewords, so you'll also get

Bareword "i" not allowed while "strict subs" in use

That error oddly comes after the error you mentioned.

Sign up to request clarification or add additional context in comments.

3 Comments

what about with use strict;? I have that set.
@ewok With use strict, bareword i is an error regardless of ++ or not.
@ewok, Adjusted wording.
5

You can use ${\($var++)} to increment the variable while interpolating it.

use strict ;
use warnings ;

my $var = 5 ;

print "Before:     var=$var\n" ;
print "Incremented var=${\($var++)}\n" ;
print "After:      var=$var\n" ;

This will print

Before:     var=5
Incremented var=6
After:      var=6

But I would suggest as mentioned in the comments not to use this code because using printf is easier to write and read.

7 Comments

But why would you want to!?
can this be done with postincrement? i.e. print "${\($var++)}\n"?
@ewok Yes you can.
@ikegami can you explain why this is bad?
Complexity is something one should strive to avoid.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.