perl - Increment variables in files -


i complete rookie perl. trying open list of files, increment 3 different variables in each file, save files, , close.

the variables this

this_is_my_variable03 this_is_my_variable02 this_is_my_variable01 

the variable ending in 01 in file multiple times. variables @ times part of character string. this_is_my_variable part of variable never changes.

thanks.

this may not best solution works

#!perl=c:\ibm\rationalsdlc\clearcase\bin\perl  use warnings; use strict;  use tie::file;  tie @data, 'tie::file', 'myfile.txt' or die $!;  s/(this_is_my_variable)(\d+)+/$1.++($_=$2)/eg @data;  untie @data; 

thank borodin getting me started tie::file: helped.

second solution using while loop

#!perl=c:\ibm\rationalsdlc\clearcase\bin\perl use warnings;  #use strict;  sub inc {     ($num) = @_;     ++$num; }  open(file, "myfile.txt") || die $!; $i = 0; while (<file>) {     $string = $_;     if (/this_is_my_variable../) {         $string =~ s/(this_is_my_variable)(\d+)+/$1.++($_=$2)/eg;         print "$string \n";         $i++;     }     else {         print "$string \n";     } }  close file; 

your "second solution using while loop" has number of problems.

  • never disable use strict program working. hide problems in code

  • you have unused subroutine inc , unused variable $i

  • you should use three-parameter form of open, , lexical file handles

  • there no need test whether line contains string before applying substitution

  • you can use ($2+1) in replacement string, rather assigning value $_ , incrementing ++($_=$2)

  • if going use named variable lines read file, should use while (my $string = <$fh>) {...}. short blocks better use $_

  • you don't chomp input, fine except printing additional space , newline after each line

  • you have print "$string \n" in code twice. may appear once outside if structure

this code performs same process. hope helps.

use strict; use warnings;  open(my $fh, '<', 'myfile.txt') || die $!; while (<$fh>) {     s/(this_is_my_variable)(\d+)/$1.($2+1)/eg;     print; } 

Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -