Carnival has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
I'm a novice Perl writer in need of a bit of help.
I need to carry out several substitutions, on the contents of several files, in several directories.. if that makes sense!
Currently I have all my substitutions as one-liners which execute on the current working directory, but I would like to combine them all into a single clean script.
Simple explanation for what I would like to do:chdir to dir1 for contents of each file in dir1 do s/blue/red/; s/yellow/green/; close dir1 chdir to dir2 for contents of each file in dir2 do s/purple/orange/; close dir2 chdir to dir3 etc..
How would I do this? I have a test script below, the first part of which successfully chdirs to /attach and changes the filenames to lowercase. The second part is one of the scripts to change the contents of each file in a dir. I'm not sure if I'm headed in the right direction or not (or if any of this is salvageable?).
#!/usr/bin/perl use strict; use warnings; use File::Copy; ### Convert all filenames within /attach subdir to lowercase ### my $attchdir = '/attach'; chdir($attchdir) or die "Can't chdir to $attchdir $!"; opendir(ATTCHDIR, $attchdir) || die "Couldn't opendir: $!\n"; my @attchfiles = grep { $_ ne '.' && $_ ne '..' } readdir ATTCHDIR; foreach(@attchfiles) { my $attchfilename = $_; $attchfilename =~ tr/A-Z/a-z/; rename($_, $attchfilename); } closedir(ATTCHDIR); ### ### my $dir = '/html'; opendir(DIR, $dir) or die "Cannot open directory: $!\n"; my @files = readdir(DIR); closedir(DIR); foreach(@files) { my $filename = $_; open(FILE, $filename); while (my $data = <FILE>) { #print $data; $data =~ s/red/blue/g; } close(FILE); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How would I write this multiple substitution script?
by moritz (Cardinal) on Oct 13, 2011 at 09:31 UTC | |
|
Re: How would I write this multiple substitution script?
by bart (Canon) on Oct 13, 2011 at 09:33 UTC | |
|
Re: How would I write this multiple substitution script?
by fisher (Priest) on Oct 13, 2011 at 09:26 UTC | |
|
Re: How would I write this multiple substitution script?
by Carnival (Novice) on Oct 13, 2011 at 10:44 UTC | |
|
Re: How would I write this multiple substitution script?
by hbm (Hermit) on Oct 13, 2011 at 15:08 UTC | |
|
Re: How would I write this multiple substitution script?
by TomDLux (Vicar) on Oct 13, 2011 at 19:35 UTC | |
|
Re: How would I write this multiple substitution script?
by Carnival (Novice) on Oct 14, 2011 at 07:57 UTC |