patgas has asked for the wisdom of the Perl Monks concerning the following question:
So besides reading PM and playing Perl golf all day at work, I occasionally get to use Perl to actually do some work. Like today, for example... A coworker wanted a bunch of HTML files in a directory renamed to be ASP files. Simple enough, I just:
#!/usr/bin/perl -w use strict; my $dir = shift; opendir DIR, $dir or die "Can't open $dir: $!"; foreach my $file ( grep /\.html|\.htm$/i, readdir DIR ) { ( my $newfile = $file ) =~ s/\.html|\.htm$/\.asp/i; rename "$dir\\$file", "$dir\\$newfile"; print "Changing $dir\\$file to $newfile\n"; } closedir DIR;
And later, when she asked if it were possible to search and replace text in a whole bunch of files, I proudly smiled and said, "Absolutely." So then I:
#!/usr/bin/perl -w use strict; my $dir = shift; opendir DIR, $dir or die "Can't open $dir: $!"; foreach my $file ( grep /\.asp$/i, readdir DIR ) { my $target = "<html>\n" . "<head>\n" . "<title>[^>]*<\/title>\n" . "<meta http-equiv=\"Content-Type\" content=\"text\/ht +ml; charset=iso-8859-1\">\n" . "<\/head>\n\n" . "<body bgcolor=[\"]#FFFFFF[\"]>"; my $target2 = "<HTML>\n" . "<HEAD>\n" . "<TITLE>[^>]*<\/TITLE>\n" . "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text\/h +tml; charset=iso-8859-1\">\n" . "<\/HEAD>\n" . "<BODY BGCOLOR=#FFFFFF>"; my $replace = "<!-- #include file=\"popupHeader\.asp\" -->"; print "Changing $dir\\$file..."; open FILE, "$dir\\$file" or die "Can't open $dir\\$file: $!"; my $text; { local $/ = undef; $text = <FILE>; } $text =~ s/$target/$replace/; $text =~ s/$target2/$replace/; close FILE; open FILE, ">$dir\\$file"; print FILE $text; close FILE; print "Done.\n"; } closedir DIR;
Now I was pretty pleased with myself that I've become acquainted enough with Perl to be able to write such awe-inspiring (at least to my coworker) scripts in about 20 minutes. What I'd like to know now is, how can I improve them? What did I do wrong? Is there a way to simplify them, so next time it comes up, it'll only take 5 minutes to write them?
"We're experiencing some Godzilla-related turbulence..."
|
|---|