in reply to serialze text in a file

Your algorithm sounds right. Here is one way to do it:
use strict; use warnings; my $i = 1; while (<DATA>) { if (s/(LKTA_mic)\d/$1$i/) { $i = ($i == 4) ? 1 : $i + 1; } print; } __DATA__ Name - John filename "LKTA_mic4.cfg"; } Name - Tim filename "LKTA_mic2.cfg"; } Name - Jane filename "LKTA_mic1.cfg"; } Name - Jim filename "LKTA_mic3.cfg"; } Name - Don filename "LKTA_mic1.cfg"; } Name - Cody filename "LKTA_mic4.cfg"; }

prints out:

Name - John filename "LKTA_mic1.cfg"; } Name - Tim filename "LKTA_mic2.cfg"; } Name - Jane filename "LKTA_mic3.cfg"; } Name - Jim filename "LKTA_mic4.cfg"; } Name - Don filename "LKTA_mic1.cfg"; } Name - Cody filename "LKTA_mic2.cfg"; }

Update: changed to use capturing in regex.

Also, Search and replace

Replies are listed 'Best First'.
Re^2: serialze text in a file
by biohisham (Priest) on Jul 08, 2009 at 14:37 UTC
    Hey, I am learning regex now, it is like head-hammering at someplaces hehe...anyways I wanted to ask you, in this line you wrote,
    if(s/(LKTA_mic)\d/$1$i/)
    ok, I see that you are using backreferences to (LKTA_mic), but the way you used the variable $i, I mean, if these files were different, each one of them was a different identity in DATA, and each one of them had its unique number though the arrangement was not serial still, would they be physically re-arranged or ...according to what I could elicit here, they are merely being renamed instead? so the DATA file
    Name - John filename "LKTA_mic4.cfg"; }
    would be renamed to
    Name - John filename "LKTA_mic1.cfg"; }
    with contents intact and so on...?
    ##excuse my ignorance but slight not my attempts to learn##
      Yes, my code does a simple text substitution, replacing a single digit (0 through 9) with the value in the $i variable.