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 strictprogram working. hide problems in codeyou have unused subroutine
inc, unused variable$iyou should use three-parameter form of
open, , lexical file handlesthere 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
chompinput, fine except printing additional space , newline after each lineyou have
print "$string \n"in code twice. may appear once outsideifstructure
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
Post a Comment