Greeting fellow monks,
I feel rather embarrased asking this question, but here goes anyway. (It's an optimization plus question.) I've recently written a little thingy that essentially lets the novice/newbie change strings within several files in a directory tree. It's written so that it'll run on both UNIX (via command line) and Win32 (via icon double click) systems.
It works, mostly. Biggest problem is that I tried to use the thing on UNIX to remove those pesky "\r"s that Windows puts in text files. Well, it ended up dumping all "\n"s as well. :(
My question/plea for assistance is two fold and thus: Can someone help me figure out why I can't substitute "\n" for "\r\n"? More importantly, and the bigger issue, there are several parts of this code that are really newbie and inefficient (both in run-speed and # of lines). Can anyone suggest how I might reduce some of the lines here? Thanks.
#!/usr/bin/perl use strict; use Cwd; use File::Find; my $changefrom; while ($changefrom eq '') { print "Change (Pattern): "; $changefrom = <>; chomp($changefrom); } print "To... (Pattern): "; my $changeto = <>; chomp($changeto); print "Match files [.]: "; my $match_files = <>; chomp($match_files); $match_files = '.' if ($match_files eq ''); my $cwd = cwd(); print "Directory [$cwd]: "; my $startdir = <>; chomp($startdir); $startdir = $cwd if ($startdir eq ''); print "Case Sens (y/n) [n]: "; my $case = <>; chomp($case); my $change_files_count = 0; my $change_times_count = 0; print "Starting search & changes...\n"; &find(\&wanted, $cwd); if ($change_files_count == 0) { print "Done! Didn't find any files to change.\n"; } else { print "Done! Made $change_times_count changes ", "in $change_files_count files.\n"; } if (($^O =~ /MS/i) && ($^O =~ /Win/i)) { print "\nPress return to exit. "; my $ending = <>; } exit; sub wanted { if ((-f) && ($_ =~ /$match_files/)) { open(DEFILE, $_) || print "Can't open file: $!\n"; my @file_contents = <DEFILE>; close(DEFILE); my $happens; if (($case eq "y") || ($case eq "Y")) { $happens = grep(/$changefrom/, @file_contents); } else { $happens = grep(/$changefrom/i, @file_contents); } if ($happens > 0) { print "Changing \"$File::Find::name\" file...\n"; my $file_contents = join('', @file_contents); if (($case eq "y") || ($case eq "Y")) { $file_contents =~ s/$changefrom/$changeto/g; } else { $file_contents =~ s/$changefrom/$changeto/gi; } open(DAFILE, "> $_") || print "Can't write to file: $!\n"; print DAFILE $file_contents; close(DAFILE); $change_times_count += $happens; $change_files_count++; } } }
Thanks in advance. :) Keep in mind that I need this to run on both UNIX and Win32, and it needs to be very user friendly. As in, the most basic novice could figure it out.
-Gryphon.
In reply to Change utility; code optimization by gryphon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |