SuedeBlur has asked for the wisdom of the Perl Monks concerning the following question:

How difficult would it be to write a script in Perl to scan entire trees looking to replace every occurrence of a command such as 'Name' with another command such as 'FullName' for a given file type such as *.INF?
  • Comment on Replacing one string with another string

Replies are listed 'Best First'.
Re: Replacing one string with another string
by merlyn (Sage) on Aug 18, 2000 at 06:20 UTC
    use File::Find; find sub { push @ARGV, $File::Find::name if /\.INF$/; }, "."; $^I = ".BAK"; while (<>) { s/Name/Fullname/g; print; }
    Not too tough. About that tough.

    -- Randal L. Schwartz, Perl hacker

      Just a simpleton question .. but why do you do subname sub { # code .. # }
      and not sub subname { # code .. # }
      this doesnt seem to compile on my install of perl (5.6)


      lindex
      /****************************/ jason@gost.net, wh@ckz.org http://jason.gost.net /*****************************/
Re: Replacing one string with another string
by elusion (Curate) on Aug 18, 2000 at 05:30 UTC
    I don't know what type of a file .inf is, but it should be rather easy today, using the split command. Doing something like this:
    open(DATA,"file.inf"); #opens file @array = <DATA>; #assigns data to an array close(DATA); #closes the file @array =~ s/Name/Fullname/g; #substitutes Name with Fullname throughou +t the file open(DATA,">file.inf"); #opens file for writing print DATA @array; #prints data to the file close(DATA); #closes the data

    - p u n k k i d
    "Reality is merely an illusion, albeit a very persistent one." -Albert Einstein

      =~ doesn't operate on arrays (at least not in 5.005)
      @a = ("one","two","three"); @a =~ s/[oe]/_/g; print join("\n",@a),"\n";
      yields a compilation error
      Can't modify array deref in substitution at t.pl line 2, near "s/[oe]/ +_/g;"
      open(DATA,"file.inf") || die "can't open: $!"; local $/; # make a local copy of $/ so we don't trample other fi +lehanles undef $/; # undef it $file = <DATA>; # so we can slurp up the whole file in one bang $file =~ s/Name/Fullname/g;
      is probably more what like what you were aiming at. But merlyn's (excellent as always) solution is the one I'd end up using.

      /\/\averick