Search code examples
perlincrementstring-interpolation

perl: increment variable inside string interpolation


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 (++)


Solution

  • 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.