How do I substitute with an evaluated expression in Perl?

前端 未结 3 789
梦谈多话
梦谈多话 2021-02-20 13:15

There\'s a file dummy.txt

The contents are:

 9/0/2010
 9/2/2010
 10/11/2010

I have to change the month portion (0,2,11) to +1, ie, (1,3

3条回答
  •  孤独总比滥情好
    2021-02-20 14:15

    this works: (e is to evaluate the replacement string: see the perlrequick documentation).

    $line = '8/10/2010';
    $line =~ s!/(\d+)/!('/'.($1+1).'/')!e;
    
    print $line;
    

    It helps to use ! or some other character as the delimiter if your regular expression has / itself.


    You can also use, from this question in Can Perl string interpolation perform any expression evaluation?

    $line = '8/10/2010';
    $line =~ s!/(\d+)/!("/@{[$1+1]}/")!e;
    
    print $line;
    

    but if this is a homework question, be ready to explain when the teacher asks you how you reach this solution.

提交回复
热议问题